switch

zeph zephjc at gmail.com
Tue Dec 8 22:24:20 EST 2009


>
> Even better (well, shorter!):
> options = {"a" : do_a, "b",do_b, "c", do_c}
> options.get(option, do_default)()
>

You can also make it something callable like so, which is a little
more compact if you need to reuse it a lot:

>>> def do_a(x): print "a:", x
...
>>> def do_b(x): print "b:", x
...
>>> def do_c(x): print "c:", x
...
>>> do_something = {"a":do_a, "b":do_b, "c": do_c}.get
>>> do_something('a')(4)
a: 4
>>> do_something('c')(5)
c: 5
>>> do_something
<built-in method get of dict object at 0x6de40>
>>> do_something('d')
>>> do_something('d')(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable



More information about the Python-list mailing list