Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how binding works

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?

like image 417
gruszczy Avatar asked Nov 27 '10 15:11

gruszczy


People also ask

What does bind () do in Python?

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port.

How does bind work in tkinter?

In Tkinter, bind is defined as a Tkinter function for binding events which may occur by initiating the code written in the program and to handle such events occurring in the program are handled by the binding function where Python provides a binding function known as bind() where it can bind any Python methods and ...

What is data binding in Python?

The Python binding uses the Python pack() and unpack() functions to convert data between a Caché %BinaryOpens in a new tab and a Python list of integers. Each byte of the Caché binary data is represented in Python as an integer between 0 and 255.

How does Python interact with C?

The Python/C API allows the library to define functions that are written in C but still callable from Python. The API is very powerful and provides functions to manipulate all Python data types and access the internals of the interpreter. The second way to use the C API is to embed Python in a program written in C.


1 Answers

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)?

like image 156
cschol Avatar answered Nov 07 '22 21:11

cschol