Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 546
MeLight Avatar asked Jul 12 '26 10:07

MeLight


1 Answers

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?

like image 119
Juh_ Avatar answered Jul 14 '26 00:07

Juh_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!