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 following 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.
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')