1

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

1
  • 1
    Its truly a matter a choice- I've numerous different people say they like to keep __init__.py empty or only do basic init stuff. You could define an __all__ in __init__.py and than, from models import * Commented Jun 7, 2011 at 15:55

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

You could do this same thing in the __init__.py
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.