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()
We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.
In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.
The syntax of a lambda function is lambda args: expression . You first write the word lambda , then a single space, then a comma separated list of all the arguments, followed by a colon, and then the expression that is the body of the function.
The whole lambda function lambda x : x * x is assigned to a variable square in order to call it like a named function. The variable name becomes the function name so that We can call it as a regular function, as shown below. The expression does not need to always return a value.
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.
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 evaluatesx
; ifx
is true, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With