python - Importing a module at runtime -
i'm trying import module using __import__()
. need use __import__
becuase don't know module i'll need before runtime.
let's module i'll need myclass
. file tree api/apps/myapp/my_class.py
, , class have in my_class.py
myclass
. now, access methods of myclass
i'm doing this:
my_class_module = __import__('api.apps.myapp.my_class') my_class= my_class_module.myclass()
but i'm getting error: 'module' object has no attribute 'myclass'
any ideas?
by default, __import__
return reference first module. in example, api
. solution use fromlist
parameter:
my_class_module = __import__('api.apps.myapp.my_class', fromlist=[''])
from __import__
documentation:
[...] when importing module package, note ___import___('a.b', ...) returns package when fromlist empty, submodule b when fromlist not empty. [...]
for details on reason so, see why python's __import__ require fromlist?
Comments
Post a Comment