Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string into a function call

Tags:

python

I have a string variable with the exact name of a function, e.g.

ran_test_opt = "random_aoi"

The function looks like this:

def random_aoi():
  logging.info("Random AOI Test").

The string is received from a config file and therefore can't be changed. Is there a way I can convert the string into an actual function call so that

ran_test_opt()

would run the random_aoi function?

like image 208
Marmstrong Avatar asked Feb 25 '14 16:02

Marmstrong


People also ask

How do I convert a string to a function?

To convert a string in to function "eval()" method should be used. This method takes a string as a parameter and converts it into a function.

Can you use a string to call a function?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method.

How do you make a str object callable?

The result was the TypeError: 'str' object is not callable error. This is happening because we are using a variable name that the compiler already recognizes as something different. To fix this, you can rename the variable to a something that isn't a predefined keyword in Python. Now the code works perfectly.

How do you use a string function in Python?

Python string encode() function is used to encode the string using the provided encoding. Python String count() function returns the number of occurrences of a substring in the given string. Python string startswith() function returns True if the string starts with the given prefix, otherwise it returns False.


2 Answers

Sure, you can use globals:

func_to_run = globals()[ran_test_opt]
func_to_run()

Or, if it is in a different module, you can use getattr:

func_to_run = getattr(other_module, ran_test_opt)
func_to_run()
like image 135
mgilson Avatar answered Sep 30 '22 04:09

mgilson


there is another way to call a function from a string representation of it just use eval("func()") and it will execute it

like image 44
zerocool Avatar answered Sep 30 '22 05:09

zerocool