Functions aren't mutable in general; but they may have references to data that is. In your snippet, this reference is a little unclear, but i
only occurs once in the function body, as a read. It therefore reads from some outer scope, typically the function or module your for
loop is contained within. Because this happens to be a shared context, every addi
function will end up with the same i
.
Another issue is that you're using the name addi
on every iteration, and the function never appeared under another name. So whatever addi
functions were defined earlier are lost. This leads us to the third question; why would you want to create names (such as function names) dynamically? It's almost always better to use a collection, such as the d
dictionary in jpp's answer. Otherwise, what code would even refer to the functions you created?
All that said, it is still possible to do what you asked for, albeit very strange. Here's one way:
def addfunc(n):
def addn(x):
return x+n
return addn
for i in range(1,10):
globals()['add{}'.format(i)] = addfunc(i)
This abuses globals
to inject dynamically created names into the module's namespace, and nests each of these functions within another to create the namespaces holding their individual n
values. Another classic hack was using a default argument, and partial application of operator.add
is a neater functional style.