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?

asked Aug 19, 2016 at 0:29

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()
answered Aug 19, 2016 at 0:35
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)]
answered Aug 19, 2016 at 0:32

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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.