Using for loop to define multiple functions - Python
Use functools.partial
combined with a dictionary in this situation.
I assume what you really want to do is more complex, since multiple functions are not necessary for this specific task.
from functools import partial
def add(x, i):
return x + i
d = {f'add{k}': partial(add, i=k) for k in range(1, 10)}
d['add3'](5) # 8
Explanation
- It is good practice to store a variable number of related objects in a specially defined dictionary.
functools.partial
is a higher order function which returns an input function with selected argument(s) fixed.
Polluting the namespace
From the comments, a commonly asked question goes:
OP seems to be asking if there's a better way of just doing
def add1:
...def add2:
... While I agree with your solution, I don't agree with the fact that it's the solution to the current question. - MooingRawrWhy is using an iterator to define functions a bad idea? It seemed like a good way to shorten code to me. Is it generally better to define them one by one? – jessica
My short answer:
Using
globals().update
to pollute the namespace is a bad idea.. Hold related variables in specially made collections. It makes sense from any viewpoint (maintainability, calling, modifying, etc). – jpp
@BoarGules's extend answer:
It's not a good idea because it creates functions dynamically, but they can only be called by static code (otherwise the code wouldn't know what to call), so what's the point of them being dynamic? Creating them dynamically makes the code hard to read (you can't easily search for the function definition) and gives IDEs unnecessary trouble in their efforts to help you. You save tedious, repetitive coding, but programming sometimes entails tedious and careful repetition. The effort and skill would be better spent speeding up the coding (clever search/replace, macros, whatever). – BoarGules
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.
A solution:
from types import FunctionType
from copy import copy
def copy_function(fn, name):
return FunctionType(
copy(fn.func_code),
copy(fn.func_globals),
name=name,
argdefs=copy(fn.func_defaults),
closure=copy(fn.func_closure)
)
for i in range(10):
name = 'add' + str(i)
def _add(x):
return x + (i+1)
globals()[name] = copy_function(_add, name)
print add1(2) # 4
print add3(8) # 12
Using the copy function from https://stackoverflow.com/a/34796018/7529716
For Python3, change copy_function to:
def copy_function(fn, name):
return FunctionType(copy(fn.__code__),
copy(fn.__globals__), name=name, argdefs=copy(fn.__defaults__),
closure=copy(fn.__closure__))