Python Pseudo-Switch
Jason Mobarak
jason.mobarak at gmail.com
Sun May 8 00:50:01 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) }
>
class CaseThing:
def pref_A (self, x):
return x["bob"]
def pref_B (self, x):
return x["carol"]
def pref_C (self, x);
return "Ted"
def pref_D (self, x)
return do_something(x)
def getThing (self, x):
attr = getattr(self, 'pref_%s' % (x,))
if attr is not None:
return attr
else:
raise SomeError("Thing %s does not exist" % (x,))
my_thing = CaseThing().getThing(get_value_from_thin_air)(adict)
You can do something similar with method decorators for more complex
strings than what's allowed for python method names.
> 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?
>
> James
>
> --
> James Stroud
> UCLA-DOE Institute for Genomics and Proteomics
> Box 951570
> Los Angeles, CA 90095
>
> http://www.jamesstroud.com/
More information about the Python-list
mailing list