Python – Possibilities for Python classes organized across files?


I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes.

Best Solution

A Python file is called a "module" and it's one way to organize your software so that it makes "sense". Another is a directory, called a "package".

A module is a distinct thing that may have one or two dozen closely-related classes. The trick is that a module is something you'll import, and you need that import to be perfectly sensible to people who will read, maintain and extend your software.

The rule is this: a module is the unit of reuse.

You can't easily reuse a single class. You should be able to reuse a module without any difficulties. Everything in your library (and everything you download and add) is either a module or a package of modules.

For example, you're working on something that reads spreadsheets, does some calculations and loads the results into a database. What do you want your main program to look like?

from ssReader import Reader
from theCalcs import ACalc, AnotherCalc
from theDB import Loader

def main( sourceFileName ):
    rdr= Reader( sourceFileName )
    c1= ACalc( options )
    c2= AnotherCalc( options )
    ldr= Loader( parameters )
    for myObj in rdr.readAll():
        c1.thisOp( myObj )
        c2.thatOp( myObj )
        ldr.laod( myObj )

Think of the import as the way to organize your code in concepts or chunks. Exactly how many classes are in each import doesn't matter. What matters is the overall organization that you're portraying with your import statements.