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

chimeracoder picture chimeracoder · Jan 20, 2011 · Viewed 7.3k times · Source

In Java, this question is easy (if a little tedious) - every class requires its own file. So the number of .java files in a project is the number of classes (not counting anonymous/nested classes).

In Python, though, I can define multiple classes in the same file, and I'm not quite sure how to find the point at which I split things up. It seems wrong to make a file for every class, but it also feels wrong just to leave everything in the same file by default. How do I know where to break a program up?

Answer

Jim Brissom picture Jim Brissom · Jan 20, 2011

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.