简体   繁体   中英

Rationalising package structure in python

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

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.

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

Create 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM