MeLight
MeLight

Reputation: 5565

Importing a module at runtime

I'm trying to import a module using __import__(). I need to use __import__ becuase I don't know which module I'll need before runtime.

Let's say the module I'll need is MyClass. The file tree is api/apps/myapp/my_class.py, and the class i have in my_class.py is MyClass. Now, to access the methods of MyClass what I'm doing is this:

my_class_module =  __import__('api.apps.myapp.my_class')
my_class= my_class_module.MyClass()

But I'm getting this error: 'module' object has no attribute 'MyClass'

Any ideas?

Upvotes: 3

Views: 1558

Answers (1)

Juh_
Juh_

Reputation: 15539

By default, __import__ return a reference to the first module. In your example, it is api. The solution is to use the fromlist parameter:

my_class_module =  __import__('api.apps.myapp.my_class', fromlist=[''])

From the __import__ documentation:

[...] When importing a module from a package, note that ___import___('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty. [...]

For details on the reason it does so, see Why does Python's __import__ require fromlist?

Upvotes: 3

Related Questions