if/elif chain with assignment expressions

Larry Bates lbates at swamisoft.com
Mon Jul 12 16:45:51 CEST 2004


What about:

e_list=[{'condition': 'f(y) < 5', 'call': fred},
        {'condition': 'f(y) < 7', 'call': ted},
        {'condition': 'f(y) < 9', 'call': ned}]

for e in e_list:
    if eval(e['condition']):
        e['call'](y)
        break

Its easily extendable and would support an unlimited
number of function calls and conditions by merely
extending e_list definition.  It also already works
with current implementation of Python.

HTH,
Larry Bates
Syscon, Inc.


"Paul Rubin" <http://phr.cx@NOSPAM.invalid> wrote in message
news:7xvfguflq1.fsf_-_ at ruckus.brouhaha.com...
> Sometimes you want to compute an expression, then do something with
> the value if it meets a certain criterion; otherwise, try a different
> expression (and maybe different criterion) instead, etc.  With := as
> an assignment expression operator, you could write:
>
>    if (y := f(x)) < 5:
>        fred(y)
>    elif (y := g(x)) < 7:
>        ted(y)
>    elif (y := h(x)) < 9:
>        ned(y)
>    etc.
>
> Of course there are alternative ways of doing the same thing, but they
> all seem to be messier.





More information about the Python-list mailing list