Can anyone explaine that behavior of lambda functions?
import sys
X = lambda: sys.stdout.write('first');sys.stdout.write("second")
X()
Returns: -> secondfirst
And one more problem:
lambda: sys.stdout.write("...");sys.exit(0) 
Or
lambda: sys.exit(0);sys.stdout.write("...")
Doesn't execute correctly. And one more question, why in first primer execution flow goes from right to left?
Trying with: Python3+(3.4, 3.2) OS: Linux (Ubuntu), OSX
Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.
In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body.
The syntax for lambda is:
lambda <args>: <expression>
where <expression> must be a single expression. It cannot be a statement, or multiple statements, or multiple expressions separated by ;.
What happens in your code is that lambda has higher priority over ;, so that gets parsed as: X = lambda: sys.stdout.write('first') followed by sys.stdout.write("second"). Adding parentheses around sys.stdout.write('first') ; sys.stdout.write("second") would not work and produce a syntax error.
My trick to do multiple things inside a lambda is:
f = lambda: [None, sys.stdout.write('first'), sys.stdout.write("second")][0]
and the other one:
f = lambda: [None, sys.stdout.write("..."), sys.exit(0)][0]
However that kind of defeats the purpose of a lambda function, which is to do something short and really simple.
I guess that would still be OK in your specific example, but kind of looks like a hack.
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