开发者

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 cl开发者_如何学Casses 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜