Conditional structures: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 3,016: | Line 3,016: | ||
dispatcher[1]=bar |
dispatcher[1]=bar |
||
dispatcher[2]=baz # foo,bar, baz, and boz are defined functions. |
dispatcher[2]=baz # foo,bar, baz, and boz are defined functions. |
||
# Then later |
# Then later |
||
results = dispatcher.get(x, boz)() # binding results to a name is optional |
results = dispatcher.get(x, boz)() # binding results to a name is optional |
||
Line 3,021: | Line 3,022: | ||
if x in dispatcher: |
if x in dispatcher: |
||
results=dispatcher[x]()</lang> |
results=dispatcher[x]()</lang> |
||
<lang python># The above, but with a dict literal |
|||
dispatcher = { |
|||
0: foo, |
|||
1: bar, |
|||
2: baz, |
|||
} |
|||
# ... |
|||
dispatcher.get(x, boz)()</lang> |
|||
<lang python># Or without the temp variable |
|||
# (it's up to the reader to decide how "pythonic" this is or isn't) |
|||
{ |
|||
0: foo, |
|||
1: bar, |
|||
2: baz, |
|||
}.get(x, boz)()</lang> |
|||
This can be particularly handy when using [[wp:Currying|currying]] techniques, or when lambda expressions or meta-function generators (factories) can be used in place of normal named functions. |
This can be particularly handy when using [[wp:Currying|currying]] techniques, or when lambda expressions or meta-function generators (factories) can be used in place of normal named functions. |