2

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?

2 Answers 2

4

don't use a list of strings, just store the functions in the list:

fns = [function1, function2]
for fn in fns:
    fn()
Sign up to request clarification or add additional context in comments.

Comments

2

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)]

2 Comments

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)
@TadhgMcDonald-Jensen Indeed, I was updating the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.