puzzled by name binding in local function

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Thu Feb 7 03:59:56 EST 2013


Heureka!

Am 06.02.2013 15:37, schrieb Dave Angel:
 > def myfunc2(i):
>      def myfunc2b():
>          print ("myfunc2 is using", i)
>      return myfunc2b

Earlier you wrote:
> There is only one instance of i, so it's not clear what you expect.
> Since it's not an argument to test(), it has to be found in the
> closure to the function. In this case, that's the global namespace.
> So each time the function is called, it fetches that global.

Actually, the important part missing in my understanding was the full 
meaning of "closure" and how it works in Python. After failing to 
understand how the pure Python version of functools.partial worked, I 
started a little search and found e.g. "closures-in-python"[1], which 
was a key element to understanding the whole picture.

Summary: The reason the above or the pure Python version work is that 
they use the closure created by a function call to bind the values in. 
My version used a loop instead, but the loop body does not create a 
closure, so the effective closure is the surrounding global namespace.

:)

Uli


[1] http://ynniv.com/blog/2007/08/closures-in-python.html




More information about the Python-list mailing list