How to call a function of a module from a string with the function's name in Python?


Objects in python have instance variables and methods as attributes. To call a function of a module from a string with the function's name in Python, you can get this attribute first and call the function object attached to it. For example, let's say that I have a module foo, and I have a string whose contents are "bar". The best way to go about calling foo.bar() is:

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

If you have the function in global or local namespace without the module prefix, you can also use globals()/locals(). locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

For example

>>> result = locals()["myfunction"]()
or
>>> result = globals()["myfunction"]()

Updated on: 11-Dec-2019

673 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements