Stupid Lambda Tricks [LONG]
Luigi Ballabio
ballabio at mac.com
Thu Feb 21 09:05:46 EST 2002
Hi,
At 09:51 AM 2/21/02 +0000, Gerson Kurz wrote:
>* Using IF statements
>
>4.16. Is there an equivalent of C's "?:" ternary operator?
<snip>
>This method is of course trivially defined as lambda:
>
>IF = lambda a,b,c:(a and [b] or [c])[0]
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
Bye,
Luigi
More information about the Python-list
mailing list