I am trying to understand, how exactly variable binding in python works. Let's look at this:
def foo(x):
def bar():
print y
return bar
y = 5
bar = foo(2)
bar()
This prints 5 which seems reasonable to me.
def foo(x):
def bar():
print x
return bar
x = 5
bar = foo(2)
bar()
This prints 2, which is strange. In the first example python looks for the variable during execution, in the second when the method is created. Why is it so?
To be clear: this is very cool and works exactly as I would like it to. However, I am confused about how internal bar function gets its context. I would like to understand, what happens under the hood.
EDIT
I know, that local variables have greater priority. I am curious, how python knows during execution to take the argument from a function I have called previously. bar
was created in foo
and x
is not existing any more. It have bound this x
to the argument value when function was created?
The second example implements what is called a closure. The function bar
is referencing the variable x
from its surrounding context, i.e. the function foo
. This precedes the reference to the global variable x
.
See also this question Can you explain closures (as they relate to Python)?