Loops do not introduce a scope in Python, so all three functions are closed by the same variable i and will refer to its final value after the loop ends, which is 2.
It seems that almost everyone with whom I speak, who uses closure in Python, have been bitten by this. The consequence is that an external function can change i , but an internal function cannot (since that would make i local rather than a closure based on Python syntax rules).
There are two ways to solve this problem:
# avoid closures and use default args which copy on function definition for i in xrange(3): def func(x, i=i): return x*i flist.append(func)
Walter mundt
source share