kgb26 kgb26 - 8 months ago 24
Python Question

How to call a function from a module name that is assigned to a variable

I am trying to call a function from a module. The module and the function have the same name, which is read at runtime using

and stored in a variable.

For example,

def module():
print "x"


I can import that module using the variable
. But when I call that function using that variable I get this error:

TypeError: 'str' object is not callable

How can I call that function from the module when I don't know their name until runtime?


As Jon mentioned, you didn't save a reference to the imported module. You need that to call its functions. To actually get to the function you can use the built-in getattr function. Eg,

ent = "module"
mod = __import__(ent)
func = getattr(mod, ent)

However, using __import__ is rather unusual, and only done in special situations. Is your situation special enough to warrant its use?