Stupid Lambda Tricks [LONG]
Gerson Kurz
gerson.kurz at t-online.de
Thu Feb 21 08:04:47 EST 2002
On Thu, 21 Feb 2002 14:05:46 +0000, Luigi Ballabio <ballabio at mac.com>
wrote:
>I wouldn't advise using anything of the sort of your IF thing, because it
>doesn't short-circuit. Try this:
>
>def a():
> return 1
>def b():
> print "lengthy b() calculation, possibly with side effects"
>def c():
> print "lengthy c() calculation, possibly with side effects"
>
># Use the ternary trick:
> >>> (a() and [b()] or [c()])[0]
>lengthy b() calculation, possibly with side effects
>
># Use you IF thing instead:
> >>> IF(a(),b(),c())
>lengthy b() calculation, possibly with side effects
>lengthy c() calculation, possibly with side effects
ok, it should read
IF = lambda a,b,c:(a() and [b()] or [c()])[0]
IF(a,b,c)
if a, b or c need arguments, store them in a list and do
IF = lambda a,b,c,x:(a(x) and [b(x)] or [c(x)])[0]
More information about the Python-list
mailing list