Name bindings for inner functions.

trevor_morgan at yahoo.com trevor_morgan at yahoo.com
Sat Oct 28 17:49:01 EDT 2006


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, or something, but I'm not sure how to fix this.
 I've found the ability in python to create functions on the fly and
store and index them for later use incredibly powerful, so it'd be nice
to get past this little roadblock.




More information about the Python-list mailing list