How to call a python function using a string?

Viewed 43

I am checking to see if there are any other ways to call a python function using a string. Below are the things I tried. Are there any other ways?

def test_func():
    print("works!")

func_ref = test_func
func_name = "test_func"

# testing
func_ref()  # works
locals()[func_name]()  # works
eval(func_name)()
(func_name)()  # doesn't work
1 Answers

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)
Related