A lambda is an anonymous function object. Python completely resolves whatever is on the right side of an equation to a single anonymous object and then resolves whatever is on the left side for assignment.
x = lambda: x
first compiles lambda: x
into a function object that returns whatever happens to be in x
at the time it is called. It then rebinds x
with this function object, deleting whatever object happened to be there before.
Now x
is a function that returns whatever is in x
... which is a function that returns whatever is in x
, etc... So you can write x()()()()()()
as many times as you want, and still get that orginal lambda:x
function object.
Python functions have a local namespace but only variables assigned in the function reside there. Since x
isn't assigned in the lambda
, it's resolved in the containing scope - that is, the module level "x". An identical piece of code is
def x():
return x
Contrast this with
def x():
x = 1
return x
Now, the parameter x
is a local variable and is unrelated to the global x
.