0

If I have the name of a function stored in a string like so:

foo = 'some_function'

Assuming that I could call bar.some_function.baz(), how can I do that using foo? Obviously this example doesnt explain why I couldnt just use some_function but in the actual code I iterate over a list of names of functions that I want to call.

To make it even clearer, if bar.some_function.baz() prints 'Hello world!' then some code, using foo but not some_function should do the same. Is it perhaps possible to use the value of the string and exec()?

Thanks in advance

SneakyOrc
  • 1
  • 1

1 Answers1

0

If it's in a class, you can use getattr:

class MyClass(object):
def install(self):
      print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method() or if it's a function:

def install():
   print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
 raise NotImplementedError("Method %s not implemented" %    method_name)
method()