Don't use eval! It's almost never required, functions in python are just attributes like everything else, and are accessible either using getattr
on a class, or via 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>,
}
Since that's a dictionary, you can get the functions via the dict-keys 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