I am developing a python library with the following structure
/application
/lib
__init__.py
/models
__init__.py
model1.py
model2.py
model3.py
In each model%.py file there is a corresponding class named Model%. I like to keep these classes in their own files but it means that in my application I need to import classes from the models package like so
from models.model1 import Model1
from models.model2 import Model2
from models.model3 import Model3
Is there some way to do this instead?
from models import Model1, Model2, Model3
It feels more intuitive and more like what I am doing. I have a package called models and I want it to contain these classes but I still want each class to have its own file so I can add new models by simply adding a file.
Previously I put this in my /application/lib/models/_init_py file
from model1 import Model1
from model2 import Model2
from model3 import Model3
But I understood this was importing all the classes even when I only need one of them
3 Answers 3
Your final solution is correct. You should only worry about loading too many classes if it is causing serious performance issues, which I highly doubt.
Comments
One way is to create a file in your models directory that imports your classes, then import from that file. For example, you could create a file called api.py that contains
from model1 import Model1
from model2 import Model2
from model3 import Model3
Then you could import the models like this
from models.api import Model1, Model2, Model3
1 Comment
__init__.pyCreate separate package for each module. Put model1.py into model1 package. In __init__.py file of model1 package, put
from model1 import Model1
then, you will be able to do
from model1 import Model1
from your application.
__init__.pyempty or only do basic init stuff. You could define an__all__in__init__.pyand than,from models import *