Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #38338

Re: puzzled by name binding in local function

From Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com>
Newsgroups comp.lang.python
Subject Re: puzzled by name binding in local function
Date 2013-02-07 09:59 +0100
Message-ID <c17cu9-346.ln1@satorlaser.homedns.org> (permalink)
References <jek7u9-aaq.ln1@satorlaser.homedns.org> <mailman.1374.1360087665.2939.python-list@python.org> <fbn9u9-9fv.ln1@satorlaser.homedns.org> <mailman.1412.1360161459.2939.python-list@python.org>

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

puzzled by name binding in local function Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-05 16:18 +0100
  Re: puzzled by name binding in local function Dave Angel <davea@davea.name> - 2013-02-05 13:07 -0500
    Re: puzzled by name binding in local function Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-06 11:19 +0100
      Re: puzzled by name binding in local function Dave Angel <davea@davea.name> - 2013-02-06 09:37 -0500
        Re: puzzled by name binding in local function Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-07 09:59 +0100
  Re: puzzled by name binding in local function Terry Reedy <tjreedy@udel.edu> - 2013-02-05 14:27 -0500

csiph-web