Santiago Alessandri
Santiago Alessandri

Reputation: 6855

Python: Maintaining code in modules

I'm building a project and I have run into the following problem:

I have implemented several subclasses, each of them having about 250 lines of code. Semantically, they should go together in the same module and I want to import them with

from mymodule import SubclassA, SubclassB

But then my module file has thousands of lines, which makes maintaining its code pretty nasty. Now I have each class in a separate file to make it easier to maintain but I have to use it like this:

from subclassa import SubclassA
from subclassb import SubclassB

this does not make any sense and it's really awful.

Is there any elegant solution? If not, which of the aforementioned is the better solution?

Upvotes: 7

Views: 290

Answers (3)

Nate
Nate

Reputation: 12849

You can always put the from subclassa ... imports into your package's __init__.py as you showed in your second listing. Then, they will be available directly off of your package as you wrote in your first listing.

Upvotes: 5

Tadeck
Tadeck

Reputation: 137450

You can import both classes within mymodule module from their respective files:

import SubclassA, SubclassB

and then within other projects you can simply import these classes from this module:

from mymodule import SubclassA, SubclassB

Let me know if this is what you are looking for.

Upvotes: 0

Emilio M Bumachar
Emilio M Bumachar

Reputation: 2613

I prefer the second solution, with separate files. The imports are not that awful.

If they bother you so much, you could encapsulate them in yet another file, and then import all classes secondhand from that file. So your main import would look like the first solution, but the sole contents of the mymodule file would be the code in the second solution.

Upvotes: 1

Related Questions