Problem understanding how closures work

Gabriel Genellina gagsl-py at yahoo.com.ar
Tue Dec 12 16:41:57 EST 2006


On 12 dic, 17:23, Tom Plunket <t... at fancy.org> wrote:

> ...at least, I think that I'm having a problem understanding the way
> closures work.
>
> I'm trying to define a function for an object which will take certain
> objects from the parent scope at the time that function is defined.

> def CreateTests1(count):
>         tests = []
>         for i in xrange(count):
>                 name = 'Test %d' % i
>                 t = Test(name)
>                 tests.append(t)
>
>                 def ExCall(text):
>                         print '%s says, "%s"' % (name, text)
>
>                 t.ExternalCall = ExCall
>
>         return tests

name, inside ExCall, is a free variable. Python builds a closure
including the string whose name is "name" in the enclosing scope. Not
the *value* which happens to have at this momment. When you execute
ExCall, the reference to name yields its last, current, value.
If you want "the value at the moment the function is created" you can
use a default argument:

def ExCall(text, name=name): ...

Your second test works because you don't modify "name" between the
original definition and its execution.

-- 
Gabriel Genellina




More information about the Python-list mailing list