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)