Calling unknown Python functions

This was the best name I could come up with for the topic, and none of my searches gave information related to the issue.

How do I call a function from a string, i.e.

functions_to_call = ["func_1", "func_2", "func_3"] for f in functions_to_call: call f 
+6
python
source share
7 answers
 functions_to_call = ["func_1", "func_2", "func_3"] for f in functions_to_call: eval(f+'()') 

Edited to add:

Yes, eval () is usually a bad idea, but this is what the OP was looking for.

+2
source share

You can use python () built-in locators to get local declarations, for example:

 def f(): print "Hello, world" def g(): print "Goodbye, world" for fname in ["f", "g"]: fn = locals()[fname] print "Calling %s" % (fname) fn() 

You can use the "imp" module to load functions from custom python files, which gives you a bit more flexibility.

Using locals () ensures that you cannot call shared python, while with eval you can end up setting the user to something unpleasant, for example:

 f = 'open("/etc/passwd").readlines' print eval(f+"()") 

or similar, and ultimately your programming does what you don't expect. Using similar tricks with locals () and dicts will generally give KeyErrors to hackers.

+19
source share

how do you not know the name of the called function? Save functions instead of name:

 functions_to_call = [int, str, float] value = 33.5 for function in functions_to_call: print "calling", function print "result:", function(value) 
+15
source share

Something like this ... when I was looking at function pointers in python ..

 def myfunc(x): print x dict = { "myfunc": myfunc } dict["myfunc"]("hello") func = dict.get("myfunc") if callable(func): func(10) 
+8
source share

Take a look at the getattr function:

http://docs.python.org/library/functions.html?highlight=getattr#getattr

 import sys functions_to_call = ["func_1", "func_2", "func_3"] for f in functions_to_call: getattr(sys.modules[__name__], f)() 
+6
source share

See eval and compile functions.

This function can also be used to execute arbitrary code objects (for example, created by the compile () command). In this case, pass the code object instead of the string. If the code object was compiled with "exec" as an argument of the form, the return value of eval () will be None.

+1
source share

Do not use eval! This is almost never required, functions in python are just attributes like everything else, and are accessible either with getattr for the class or through locals() :

 >>> print locals() {'__builtins__': <module '__builtin__' (built-in)>, '__doc__': None, '__name__': '__main__', 'func_1': <function func_1 at 0x74bf0>, 'func_2': <function func_2 at 0x74c30>, 'func_3': <function func_3 at 0x74b70>, } 

With this dictionary you can get functions through the recorders func_1 , func_2 and func_3 :

 >>> f1 = locals()['func_1'] >>> f1 <function func_1 at 0x74bf0> >>> f1() one 

So, the solution without resorting to eval:

 >>> def func_1(): ... print "one" ... >>> def func_2(): ... print "two" ... >>> def func_3(): ... print "three" ... >>> functions_to_call = ["func_1", "func_2", "func_3"] >>> for fname in functions_to_call: ... cur_func = locals()[fname] ... cur_func() ... one two three 
+1
source share

All Articles