[Tutor] Use of "or" in a lambda expression

Cameron Simpson cs at zip.com.au
Sun Apr 5 05:21:23 CEST 2015


On 05Apr2015 03:34, Steven D'Aprano <steve at pearwood.info> wrote:
>On Sat, Apr 04, 2015 at 11:49:08AM -0500, boB Stepp wrote:
>> widget = Button(None,
>>             text='Hello event world!',
>>             command=(lambda: print('Hello lambda world!') or sys.exit()))
>
>That's either the most horrible misuse of lambda I've ever seen, or a
>really cool and rather nifty trick. I'm not sure which :-)

I think it is misuse. When I need to run two functions like that I tend to use 
a tuple:

  lambda: (f1(), f2())

Since Python evaluates left to right, these functions are called f1 first, then 
f2.

Using "or" introduces a reliance on f1 returning a falsish value. Dodgy and 
unreliable. Not to mention conflating the supposed Boolean value computed by 
the expression with the program's purpose.

Like others, I agree it is generally better to define a function more normally 
and just name in instead of inlining a lambda. But sometimes (rarely) that 
makes for harder to read code structure (though easier to read function 
internals).

Anyway, faced with a desire to use a lambda here, I would choose a tuple.

Cheers,
Cameron Simpson <cs at zip.com.au>

This is my simple religion. There is no need for temples; no need for
complicated philosophy. Our own brain, our own heart is our temple; the
philosophy is kindness.	- Dalai Lama


More information about the Tutor mailing list