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

Alan Gauld alan.gauld at btinternet.com
Sat Apr 4 22:35:26 CEST 2015


On 04/04/15 17:49, boB Stepp wrote:

> widget = Button(None,
>              text='Hello event world!',
>              command=(lambda: print('Hello lambda world!') or sys.exit()))

> am not understanding how 'or' causes this to happen. I guess I am
> expecting the 'or' to result only in the print running without

This is explained in more detail in the functional programming
topic of my tutorial. It's called short circuit evaluation of
boolean expressions if you want to look it up on wikipedia
or elsewhere.

The short version is that to evaluate an OR Python looks at
the first expression and if its true it returns the result
  - since any single True expression makes the OR true too.

If the first expression is false-like (eg None returned from
a print() ) then it must evaluate the second expression to
be sure of the overall OR result.

So by putting a print() which returns None, first Lutz
ensures the second expression is also evaluated.

He could have done it in various other ways too:

eg.
lambda : all(print('Hello lambda world!'), sys.exit() )

But the OR style is established as a kind of idiom,
not just in Python but several other languages too.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list