Name bindings for inner functions.

Fredrik Lundh fredrik at pythonware.com
Sat Oct 28 22:08:07 EDT 2006


trevor_morgan at yahoo.com wrote:

> The following code:
> 
> def functions():
>     l=list()
>     for i in range(5):
>         def inner():
>             return i
>         l.append(inner)
>     return l
> 
> 
> print [f() for f in functions()]
> 
> 
> returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4].  I presume
> this is something to do with the variable i getting re-bound every time
> we go through the loop

free variables bind to *names*, not objects.  all your functions will 
refer to the name "i" in "function"'s scope, which is bound to a 4 when 
the loop has finished.

you can use the default argument mechanism to explicitly bind to an 
object instead of a name:

def functions():
     l=list()
     for i in range(5):
         def inner(i=i):
             return i
         l.append(inner)
     return l

</F>




More information about the Python-list mailing list