Jump to content

Conditional structures: Difference between revisions

No edit summary
Line 3,016:
dispatcher[1]=bar
dispatcher[2]=baz # foo,bar, baz, and boz are defined functions.
 
# Then later
results = dispatcher.get(x, boz)() # binding results to a name is optional
Line 3,021 ⟶ 3,022:
if x in dispatcher:
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.
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.