Using OR operator in python lambda function
The Python programming book O Reilly has sample code that uses the OR operator in a lambda function. The text states that "[code] uses the or operator to force two expressions to run."
How and why does it 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()
source to share
The Boolean operator or
returns the first available truth value, evaluating candidates in sequence from left to right. So in your case, it is used to print first 'Hello lambda world'
as it returns None
(considered false), then it will evaluate sys.exit()
which terminates your program.
lambda: print('Hello lambda world') or sys.exit()
The expression
x or y
evaluates firstx
; ifx
true, its value is returned; otherwise it is evaluatedy
and the resulting value is returned.
source to share