python: how binding works
<p>I am trying to understand, how exactly variable binding in python works. Let's look at this:</p>

<pre><code>def foo(x):
    def bar():
        print y
    return bar

y = 5
bar = foo(2)
bar()
</code></pre>

<p>This prints 5 which seems reasonable to me.</p>

<pre><code>def foo(x):
    def bar():
        print x
    return bar
x = 5
bar = foo(2)
bar()
</code></pre>

<p>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?</p>

<p>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.</p>

<p><strong>EDIT</strong></p>

<p>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. <code>bar</code> was created in <code>foo</code> and <code>x</code> is not existing any more. It have bound this <code>x</code> to the argument value when function was created?</p>
