Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 382
Santiago Alessandri Avatar asked Oct 20 '11 12:10

Santiago Alessandri


2 Answers

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.

like image 102
Nate Avatar answered Oct 29 '22 20:10

Nate


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.

like image 21
Emilio M Bumachar Avatar answered Oct 29 '22 20:10

Emilio M Bumachar