Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

importlib: No module named

I have a folder models with a file model.py.
I want to import class Model from it and name it NamedModel.
If I do this using NamedModel = importlib.import_module("models.model.Model"), I have the followin error: No module named models.model.Model.
Although, if I use from models.model import Model, it works. How do I use importlib to import this Model?

P.S. I can’t use from models.model import Model because the name of the file and the name of the class are variables.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

import_module only… well imports modules. You need to get a class from the module as it’s attribute with getattr:

NamedModel = getattr(importlib.import_module("models.model"), 'Model')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading