0

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
Timus
  • 10,974
  • 5
  • 14
  • 28
john doe
  • 5
  • 1
  • Use strings as keys and functions as values in dictionaries. – Mechanic Pig Sep 14 '22 at 05:54
  • **Do not ever use `eval` for data that could ever possibly come, in whole or in part, from outside the program. It is a critical security risk that allows the provider of that data to run arbitrary Python code.** – Karl Knechtel Sep 14 '22 at 07:47
  • That said: there is only one way to call the function. What's different are the ways to **find** the function - by giving it a different name and using that, or by looking it up in a data structure instead of using a variable name for it, or by creating new code that indirectly looks for the function. – Karl Knechtel Sep 14 '22 at 07:50

1 Answers1

0

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)
Mohammad Jafari
  • 1,742
  • 13
  • 17