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

PythonServer Side ProgrammingProgramming

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"]()
raja
Published on 20-Dec-2017 12:09:57
Advertisements