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?
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.
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.
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.
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.
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()
there is another way to call a function from a string representation of it just use
eval("func()")
and it will execute it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With