Possible Duplicate:
Creating lambda inside a loop
In the code below, invoking any member of the returned array of closures
prints the number 4.
def go():
x = []
for i in range(5):
def y(): print i
x.append(y)
return x
I would like each member of the closure to print the number that i was when the closure was defined.
One way around this is to use default arguments:
Default arguments are evaluated when the function is created, not called, so this works as you’d expect.
A little extra info just for fun:
If you’re curious what the defaults are, you can always inspect that with the
.func_defaultsattribute (__defaults__in python3.x):This attribute is also writeable, so you can in fact change the defaults after the function is created by putting a new tuple in there.