kgb26 kgb26 - 4 months ago 8
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

raw_input()
and stored in a variable.

For example,

module.py



def module():
print "x"


run.py



ent="module"
__import__(ent)
ent()


I can import that module using the variable
ent
. 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?

Answer

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)
func()

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

Comments