17

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?

pfabri
  • 885
  • 1
  • 9
  • 25
Marmstrong
  • 1,686
  • 7
  • 30
  • 54
  • Does this answer your question? [I have a string whose content is a function name, how to refer to the corresponding function in Python?](https://stackoverflow.com/questions/7719466/i-have-a-string-whose-content-is-a-function-name-how-to-refer-to-the-correspond) – ggorlen Apr 24 '23 at 19:43

2 Answers2

31

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()
mgilson
  • 300,191
  • 65
  • 633
  • 696
2

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

zerocool
  • 3,256
  • 2
  • 24
  • 40
  • 1
    For anyone else who comes across this, it's worth noting that `eval()` can be [very dangerous](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html). The tl;dr is you need to understand what the code you're evaluating is doing and make sure it's coming from a trusted source. Otherwise, this can lead to security exploits and hacks. – Kevin Flowers Jr Sep 03 '22 at 04:40