I have a list of the names of imported functions, which I can call as follows:
from myfile import function1
from myfile import function2
function1()
function2()
How would I call the functions from a list of names? For example:
fns = ['function1', 'function2']
for fn in fns:
fn()
How would I do the above properly?
asked Aug 19, 2016 at 0:29
David542
112k211 gold badges584 silver badges1.1k bronze badges
2 Answers 2
don't use a list of strings, just store the functions in the list:
fns = [function1, function2]
for fn in fns:
fn()
answered Aug 19, 2016 at 0:35
Tadhg McDonald-Jensen
21.6k5 gold badges40 silver badges69 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can access to function objects from globals() namespace, but note that this is not a general approach, since first of all your imported objects should be callable (have __call__ attribute) and they should be present in global name space.:
for fn in fns:
try:
globals()[fn]()
except KeyError:
raise Exception("The name {} is not in global namespace".format(fn))
Example:
>>> from itertools import combinations, permutations
>>>
>>> l = ['combinations', 'permutations']
>>> for i in l:
... print(list(globals()[i]([1, 2, 3], 2)))
...
[(1, 2), (1, 3), (2, 3)]
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
answered Aug 19, 2016 at 0:32
Kasravnd
108k19 gold badges167 silver badges195 bronze badges
2 Comments
Tadhg McDonald-Jensen
I do not recommend using introspection tools for production code, there are many cases where this won't necessarily work as expected such as trying importing the module itself won't work:
import math l globals()["math.sqrt"](4)Kasravnd
@TadhgMcDonald-Jensen Indeed, I was updating the answer.
lang-py