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()
2
  • This only works for functions that return a "falsey" value and to me that means its non-obvious and so bad form. Commented Jun 2, 2017 at 5:16
  • I just lost a lot of respect for that textbook... Commented Jun 2, 2017 at 5:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.