Python Pseudo-Switch
Dan Bishop
danb_83 at yahoo.com
Sat May 7 23:09:44 EDT 2005
James Stroud wrote:
> Hello All,
>
> Because of my poorly designing a database, I have recently found it
necessary
> to explore the wonders of the Python pseudo-switch:
>
> do_case = { "A" : lambda x: x["bob"],
> "B" : lambda x: x["carol"],
> "C" : lambda x: "Ted",
> "D" : lambda x: do_something(x) }
>
> my_thing = do_case[get_value_from_thin_air()](adict)
>
>
> How to handle this kind of thing when lambda is removed from the
language,
> beside the obvious def'ing those tiny little functions?
You can always re-invent lambda.
>>> def lambda2(arg_names, expression):
... exec 'def _(%s): return %s' % (','.join(arg_names), expression)
... return _
...
>>> add = lambda2(('x', 'y'), 'x + y')
>>> add(3, 4)
7
More information about the Python-list
mailing list