The problem is not that func is overwritten, but that the value of i is evaluated when the function is called, and not when it is defined. If you want to evaluate i during the definition, put it in the function declaration, as the default argument to func .
funcs = [] for i in range(10): def func(value=i): print value funcs.append(func) for f in funcs: f()
The default arguments are evaluated once when the function is defined, so the incremental loop does not affect them. This will work just as well if you used
def func(i=i): print i
but I used the name value to indicate which name is used in this function.
source share