[Tutor] python closures

Dave Angel davea at ieee.org
Tue Dec 1 01:50:53 CET 2009


Alan Gauld wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">
> "spir" <denis.spir at free.fr> wrote
> <snip>
> I did wonder if you would need n=n but I didn't think you would need x=x.
>
> Its an interesting example and I confess I don't fully understand how 
> Python's
> naming/reference rules are working here.
>
>> to let the inner func g0 "remember" outer values.
>> Why is this idiom used, then? Has something changed, or do I miss
>> a relevant point?
>
> I thought you might need to do it if n had been a parameter of f()... but
> having tried it no, it works as above.
>
> I look forward to the explanation.
>
> Alan G.
>
>
Maybe a more complex example might show the various linkages.

glob = 42

def outer(parm1):
    free = 12
    free3 = 19
    def inner(parm2, parm3=free3):
        print "global", glob, ", free vars", parm1, free, free3, ", 
locals", parm2, parm3
    free = 49
    free3 = 48
    return inner

newfunc = outer(10)
newfunc(45)


produces output:
   global 42 , free vars 10 49 48 , locals 45 19

So when the inner() function is actually called, glob is just a global.  
parm1, fre, and free3 hold the values they ended up with when outer() 
returned, and local parm2 is passed by top-level code, while local parm3 
gets its default value assigned when "def inner(...) was executed.

Notice that the free variables free, free3, and parm1 are referring to 
the function's ending state, not to the state when the function was 
defined.  This has an impact when you've got inner being defined in a 
loop.  And this example could be made more complex if outer() is a 
generator, in which case it may not have actually ended when inner gets 
called.

HTH
DaveA


More information about the Tutor mailing list