w00d
w00d

Reputation: 5596

Python manage classes in separate files

I have a project which uses the MVC pattern.

In folder "models" I have quite many classes, each class is now has its own file. But I feel like it's not convenient, because every time I need to use a class I have to import it separately. E.g. I have many of the followings in my app source:

from models.classX import classX
from models.classY import classY

If I want to import everything at once, something like from models import * I found that I can put all sorts of import in models/__init__.py. But is it the pythonic way to do it ? What is the convention ?

Upvotes: 1

Views: 1259

Answers (3)

Eric
Eric

Reputation: 97571

Firstly, you should rename your classes and modules so that they don't match, and follow PEP8:

models/
    classx.py
        class ClassX
    classy.py
        class ClassY

Then, I'd got with this in models/__init__.py:

from models.classx import ClassX
from models.classy import ClassY

Meaning in your main code, you can do any one of:

from models import *
x = ClassX()
from models import ClassX
x = ClassX()
import models
x = models.ClassX()

Upvotes: 0

user4815162342
user4815162342

Reputation: 154886

Python is not java; please avoid the one-file-per-class pattern. If you can't change it, you can import all of them from a submodule of your models package:

# all.py: convenient import of all the needed classes
from models.classX import classX
from models.classY import classY
...

Then in your code you can write:

import my.package.models.all as models  # or from my.package.models.all import *

and proceed to use models.classX, models.classY, etc.

Upvotes: 6

Bula
Bula

Reputation: 1586

Most pythonic way is one that you're already using. You can alleviate importing by grouping your classes in modules. For example, in Django usually all application models are in a single file.

From python docs:

Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practise in production code.

Upvotes: 0

Related Questions