Regarding to python docs:
The expression argument is parsed and evaluated as a Python expression
This means that it is an expression and has a value; so you can assign it to some variable:
def sum(a,b):
return a + b
x = eval('sum(1,2)')
in your example, if you use eval
it will run the function and return None
:
>>> b = eval('test_func()')
works!
>>> b is None
True
You can also use exec
built-in function which runs code dynamically.
This function supports dynamic execution of Python code.
exec('''
def sum(a,b):
return a + b
a = sum(1,2)
print(a)
''')
prints 3
.
But all of these ways, are not good to use if you only want to run a function by its name. Just use a dictionary:
def sum(a,b):
return a + b
funcs = {
'sum': sum,
}
a = funcs['sum'](1,2)