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

boB Stepp robertvstepp at gmail.com
Sat Apr 4 20:06:59 CEST 2015


On Sat, Apr 4, 2015 at 12:34 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Apr 04, 2015 at 11:49:08AM -0500, boB Stepp wrote:
>> Windows 7, Python 3.4.3
>>
>> This code snippet is "Example 7-13" on page 383 from "Programming
>> Python, 4th ed." by Mark Lutz :
>>
>> import sys
>> from tkinter import *
>>
>> widget = Button(None,
>>             text='Hello event world!',
>>             command=(lambda: print('Hello lambda world!') or sys.exit()))
>
> o_O
>
> 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 :-)

Now that I have read (and hopefully understand) your entire response,
I am wondering the same thing in the sense that my understanding of
Python's intent is for clearly readable code and this usage isn't
clear without some thought (At least for me!).

>> widget.pack()
>> widget.mainloop()
>>
>> My question is about the lambda expression. The author states "...this
>> version uses an or operator to force two expressions to be run..."  I
>> am not understanding how 'or' causes this to happen. I guess I am
>> expecting the 'or' to result only in the print running without
>> executing sys.exit(). But that is not what happens--of course. I tried
>> substituting 'and' for 'or', but this results in only the print being
>> run! Obviously I have a significant misunderstanding of what is going
>> on.
>
>
> Both `or` and `and` are "short-circuit" operators. Here is a truth-table

I get and understand the short-circuit logic. This isn't what got me!

[...]

> expression unless needed. So this piece of code:
>
>     print(msg) or sys.exit()
>
> runs like this:
>
> (1) Evaluate the expression on the left of the operator: print(msg).
> (2) That has the side-effect of printing the message, and returns
>     the value None.

This was my 'gotcha'. I forgot (but knew) that print functions return
None. Perhaps this constant switching back and forth between using
Python 2 at work and Python 3 at home is addling my brain? Also, even
if I had recalled the return of None, I might have missed that the
"side-effect" still occurs, i.e., the actual printing.

[...]

> The `and` operator is similar, except the truth-table looks like this:
>
>
>            |a = True   False
> -----------+-----------------
> b = True   |    True   False
>     False  |    False  False

And of course since print returns None, the short-circuit evaluation
causes the sys.exit() never to be seen.

Even though I snipped out most of your very well-constructed examples,
Steve, I have to say, you have a knack for making things abundantly
clear! You tutor very well, indeed, and I am appreciative!


-- 
boB


More information about the Tutor mailing list