Calling a function of a module by using its name (a string) Calling a function of a module by using its name (a string) python python

Calling a function of a module by using its name (a string)


Assuming module foo with method bar:

import foomethod_to_call = getattr(foo, 'bar')result = method_to_call()

You could shorten lines 2 and 3 to:

result = getattr(foo, 'bar')()

if that makes more sense for your use case.

You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.


locals()["myfunction"]()

or

globals()["myfunction"]()

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.


Patrick's solution is probably the cleanest.If you need to dynamically pick up the module as well, you can import it like:

module = __import__('foo')func = getattr(module, 'bar')func()


matomo