puzzled by name binding in local function
ulrich.eckhardt at dominolaser.com
Thu Feb 7 09:59:56 CET 2013
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", 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.
More information about the Python-list