Why NOT only one class per file?

Carl Banks pavlovevidence at gmail.com
Thu Apr 5 20:25:51 EDT 2007


On Apr 4, 5:23 pm, "Chris Lasher" <chris.las... at gmail.com> wrote:
> A friend of mine with a programming background in Java and Perl places
> each class in its own separate file in . I informed him that keeping
> all related classes together in a single file is more in the Python
> idiom than one file per class. He asked why, and frankly, his valid
> question has me flummoxed.

A: Because you don't have to.

Less smart aleck: Python allows programmers to put more than one class
per file.  Given that freedom, most people didn't obey one-to-one
correspondence between classes and files.  Therefore, it's the more
common idiom in Python.


> I tried to rationalize this Python idiom by claiming a file--a single
> module--makes for a great container of code which is logically tied
> together, such as a class and its subclasses. He posited that
> directories (packages) can tie the files together just as well,

Which is not incorrect.


> and by
> having the classes as separate files, he can "diff" them to see how
> they differ, something he wouldn't be able to do with the code all in
> one file.

I agree with Bruno: feeling the need to do this is a big red flag that
the code is way too cut-and-paste.

(diff'ing different versions is useful, of course, but you can
usefully diff modules with many classes in them.)


> I also offered that having related classes under one file gives more
> direct access to those classes, e.g.:

[snip examples]

> He doesn't find my arguments convincing, so I thought I'd ask here to
> see why the Python idiom is the way it is: why should we NOT be
> placing classes in their own separate files?

There's no overwhelming reason not to, IMO.  As long you have some
organization, be it with packages or modules, everything's ok.  Most
things you have to gain or lose by doing one way or the other are of
minor importance.


Carl Banks




More information about the Python-list mailing list