if/elif chain with assignment expressions
Paul Rubin
http
Mon Jul 12 14:55:07 EDT 2004
"Larry Bates" <lbates at swamisoft.com> writes:
> 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.
It throws away the value from evaluating the condition. Also, it uses
eval a lot, which adds a lot of overhead. You wanted something like:
e_list = [{'expr': lambda: f(x), 'condition': lambda y: y<5,
'call': lambda y: fred(y)},
{'expr': lambda: g(x), 'condition': lambda y: y<7,
'call': lambda y: ted(y)},
{'expr': lambda: h(x), 'condition': lambda y: y<9,
'call': lambda y: ned(y)}]
for e in e_list:
y = e.expr()
if e.cond(y):
e.call(y)
break
which is an unbelievably contorted way of replacing a straightforward
if/elif chain. And of course that wants an assignment expression too:
for e in e_list:
if e.cond(y := e.expr()):
e.call(y)
break
More information about the Python-list
mailing list