Function returns a function

Aldo Cortesi aldo at nullcube.com
Wed Sep 7 05:59:33 CEST 2005


Thus spake Gregory Bond (gnb at itga.com.au):

> Paul Rubin wrote:
>
> >
> >     def FunctionMaker(avar, func, label):
> >        def callback():
> >           avar.set(label)
> >           func()
> >        return callback
>
> I've seen this idiom a lot and I know _what_ it does.....
> but I can't
> work _how_ it does it.  How does the name binding work so
> that "avar" in
> the returned function still references the object passed
> into the
> (long-distant!) FunctionMaker() call?
>
> Web pages / turotial ptrs etc gladly accepted.

The lexical scope within which a function is declared is
made available to the function when it is run. This is done
by storing the values of free variables within the declared
function in the func_closure attribute of the created
function object.

If you want to read more, the keyword you're looking for is
"closure" - a quick search on Google for "python closure"
should satisfy your curiosity handily. There is also a neat
recipe for inspecting the values kept in the func_closure
attribute of function objects directly:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439096






Cheers,


Aldo



--
Aldo Cortesi
aldo at nullcube.com
http://www.nullcube.com
Off: (02) 9283 1131
Mob: 0419 492 863




More information about the Python-list mailing list