Marmstrong
Marmstrong

Reputation: 1786

Convert string into a function call

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?

Upvotes: 17

Views: 16419

Answers (2)

zerocool
zerocool

Reputation: 3502

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

Upvotes: 1

mgilson
mgilson

Reputation: 309889

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()

Upvotes: 32

Related Questions