When should a Python script be split into multiple files/modules? When should a Python script be split into multiple files/modules? python python

When should a Python script be split into multiple files/modules?


Remember that in Python, a file is a module that you will most likely import in order to use the classes contained therein. Also remember one of the basic principles of software development "the unit of packaging is the unit of reuse", which basically means:

If classes are most likely used together, or if using one class leads to using another, they belong in a common package.


As I see it, this is really a question about reuse and abstraction. If you have a problem that you can solve in a very general way, so that the resulting code would be useful in many other programs, put it in its own module.

For example: a while ago I wrote a (bad) mpd client. I wanted to make configuration file and option parsing easy, so I created a class that combined ConfigParser and optparse functionality in a way I thought was sensible. It needed a couple of support classes, so I put them all together in a module. I never use the client, but I've reused the configuration module in other projects.

EDIT: Also, a more cynical answer just occurred to me: if you can only solve a problem in a really ugly way, hide the ugliness in a module. :)


In Java ... every class requires its own file.

On the flipside, sometimes a Java file, also, will include enums or subclasses or interfaces, within the main class because they are "closely related."

not counting anonymous/nested classes

Anonymous classes shouldn't be counted, but I think tasteful use of nested classes is a choice much like the one you're asking about Python.

(Occasionally a Java file will have two classes, not nested, which is allowed, but yuck don't do it.)