Reputation: 19486
I've got a list of strings of the form:
['function1', 'function2']
I'd like to execute them as methods:
function1(myVar)
function2(myVar)
programatically.
What's the 'right' way?
Upvotes: 3
Views: 91
Reputation: 3859
If those functions you wanted to invoke are in a module you can access them via getattr
import your_module
method_names = ['function1', 'function2']
for name in method_names:
func = gettattr(your_module, name)
# invoke now
func() # Pass in your arguments if needed.
Upvotes: 1
Reputation: 77912
If you really need to use function names (strings), your safest bet is to keep a mapping of allowed function names to functions, ie:
allowed_functions = {
"function1": function1,
"function2": function2,
# etc
}
then lookup that mapping:
def applyfunc(funcname, *args, **kw):
func = allowed_func.get(funcname, None)
if func is None:
raise ValueError("func '%s' is not allowed" % funcname)
return func(*args, **kw)
This is quite similar to Nils Werner's solution using locals()
but way safer (and much easier to maintain to).
Else, remember that python functions are objects (as you noticed from the above example) so if all you want is a list of functions, then it's as simple as it can get:
funcs = [function1, function2)
for func in funcs:
print func(myvar)
Upvotes: 3
Reputation: 36775
locals()
returns a dict
of all local variables in this context, your functions should be among them.
for name in list:
locals()[name](myVar)
Upvotes: 2