0

How would I go about converting a string into a function call for a function that is within the same class? I used this question to help a bit but I think it has something to do with "self.".

ran_test_opt = choice(test_options)
ran_test_func = globals()[ran_test_opt]
ran_test_func()

where test_options is a list of the names of the functions available in string format. With the above code I get the error

KeyError: 'random_aoi' 
Community
  • 1
  • 1
Marmstrong
  • 1,686
  • 7
  • 30
  • 54

2 Answers2

3

Don't use globals() (the functions are not in the global symbol table), just use getattr:

ran_test_func = getattr(self, ran_test_opt)
sloth
  • 99,095
  • 21
  • 171
  • 219
1

globals() is a function that you should use very, very rarely, it smells of mixing code and data. Calling an instance method by a name found in a string is similar, but slightly less hacky. Use getattr:

ran_test_func = getattr(self, ran_test_opt)
ran_test_func()
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79