I was surprised that this assertion fails:
x = 42 x = lambda: x assert x() == 42 It seems that x ends up recursively referring to itself, so that x(), x()(), etc. are all functions.
What is the rule used to parse this, and where is this documented?
By the way (not unexpectedly given the above), the original value of x has no references left after the lambda definition:
class X: def __del__(self): print('deleting') x = X() x = lambda: x # 'deleting' is printed here
The following is an anonymous function: lambda x: x!= "X" The first x is its parameter, and in this example, the intention is for that parameter to represent a string argument.
The Python lambda function on line 4 is a closure that captures n , a free variable bound at runtime. At runtime, while invoking the function f on line 7, the value of n is three . A Python lambda function behaves like a normal function in regard to arguments.
The variable x is created by the first assignment, and rebound with the second assignment.
Since the x in the lambda isn't evaluated until the lambda is called, calling it will evaluate to the most recently assigned value.
Note that this is not dynamic scoping - if it were dynamic, the following would print "99", but it prints "<function ...":
x = 42 x = lambda: x def test(f): x = 99 print(f()) test(x)
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