6

There is a code example in the O Reilly Programming Python book which uses an OR operator in a lambda function. The text states that "[the code] uses an or operator to force two expressions to be run".

How and why does this work?

widget = Button(None, # but contains just an expression
text='Hello event world',
command=(lambda: print('Hello lambda world') or sys.exit()) )
widget.pack()
widget.mainloop()
czolbe
  • 571
  • 5
  • 18

2 Answers2

4

Every funnction in Python returns a value. If there is no explicit return statement it returns None. None as boolean expression evaluates to False. Thus, print returns None, and the right hand side of the or expression is always evaluated.

clemens
  • 16,716
  • 11
  • 50
  • 65
2

The Boolean or operator returns the first occurring truthy value by evaluating candidates in sequence from left to right. So in your case, it is used to first print 'Hello lambda world' since that returns None (considered falsey), it will then evaluate sys.exit() which ends your program.

lambda: print('Hello lambda world') or sys.exit()

Python Documentation:

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Taku
  • 31,927
  • 11
  • 74
  • 85