Python module getting too big

Question:

My module is all in one big file that is getting hard to maintain. What is the standard way of breaking things up?

I have one module in a file my_module.py, which I import like this:

import my_module

“my_module” will soon be a thousand lines, which is pushing the limits of my ability to keep everything straight. I was thinking of adding files my_module_base.py, my_module_blah.py, etc. And then, replacing my_module.py with

from my_module_base import *
from my_module_blah import *
# etc.

Then, the user code does not need to change:

import my_module  # still works...

Is this the standard pattern?

Asked By: Neil G

||

Answers:

i’m sure there are lots of opinions on this, but I’d say you break it into more well-defined functional units (modules), contained in a package. Then you use:

from mypackage import modulex

Then use the package name to reference the object:

modulex.MyClass()

etc.

You should (almost) never use

from mypackage import *

Since that can introduce bugs (duplicate names from different modules will end up clobbering one).

Answered By: Keith

It depends on what your module is doing actually. Usually it is always a good idea to make your module a directory with an ‘__init__.py' file inside. So you would first transform your your_module.py to something like your_module/__init__.py.

After that you continue according to your business logic. Here some examples:

  • do you have utility functions which are not directly used by the modules API put them in some file called utils.py

  • do you have some classes dealing with the database or representing your database models put them in models.py

  • do you have some internal configuration it might make sense to put it into some extra file called settings.py or config.py

These are just examples (a little bit stolen from the Django approach of reusable apps ^^). As said, it depends a lot what your module does. If it is still too big afterwards it also makes sense to create submodules (as subdirectories with their own __init__.py).

Answered By: Torsten Engelbrecht

No, that is not the standard pattern. from something import * is usually not a good practice as it will import lot of things you did not intend to. Instead follow the same approach as you did, but include the modules specifically from one to another for e.g.

In base.py if you are having def myfunc then in main.py use from base import myfunc So that for your users, main.myfunc would work too. Of course, you need to take care that you don’t end up doing a circular import.

Also, if you see that from something import * is required, then control the import values using the __all__ construct.

Answered By: Senthil Kumaran
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.