Python 3.x – Execute Function Based on Function’s Name String

pythonpython-3.x

I want to call that function by extracting the first word from the string. For example my string is like:

"my_func arg_1 arg_2"
#  ^       ^     ^ second argument of function
#  ^       ^ first argument of function 
#  ^ name of the function

where my_func is a name of the function already defined.

Based on the above mention string, I want to dynamically execute the my_func function. So, my function call should be like:

my_func(arg_1, arg_2)

Currently I am trying to achieve this via using eval:

eval(command.split(' ', 1)[0])

How can I achieve this?

Best Answer

You may use locals() (or globals()) to fetch the reference of function based on string. Below is the sample example:

# Sample function
def foo(a, b):
    print('{} - {}'.format(a, b))

# Your string with functions name and attributes
my_str = "foo x y"

func, *params = my_str.split()
# ^      ^ tuple of params string
# ^ function name string

Now, pass the function string as a key to the locals() dict with *params as argument to the function as:

>>> locals()[func](*params)
x - y   # output printed by `foo` function
Related Question