Why NOT only one class per file?

Nate Finch nate.finch at gmail.com
Thu Apr 5 09:04:36 EDT 2007


So, here's a view from a guy who's not a python nut and has a long
history of professional programming in other languages (C++, C, C#,
Java)

I think you're all going about this the wrong way.  There's no reason
to *always* have one class per file.  However, there's also no reason
to have 1600 lines of code and 50 classes in one file either.  You
talk about the "changing file dance", but what about the "scroll for
30 seconds" dance?  What about the "six different conflicts in source
control because everything's in one file" dance?

I think it doesn't matter how many classes and/or functions you have
in one file as long as you keep files to a reasonable size.  If you've
ever worked on a medium to large-scale project using multiple
developers and tens or hundreds of thousands of lines of code, then
you know that keeping code separate in source control is highly
important.  If I'm working on extending one class and someone else is
working on another class... it's much less of a headache if they're in
separate files in source control.  Then you don't have to worry about
conflicts and merging.  I think that's the number one benefit for
short files (not necessarily just one class per file).

My cutoff is around 500 lines per file.  If a file goes much over
that, it's really time to start looking for a way to break it up.

Sure, if all your classes are 4 lines long, then by all means, stick
them all in one file.  But I don't think that's really any kind of
valid stance to argue from.  Sure, if you don't need organization, it
doesn't matter what organization technique you use.  But if you do
need organization, it does matter.  And I think one class per file is
an acceptable way to go about it, especially when your classes tend to
be over a couple hundred lines long.

-Nate




More information about the Python-list mailing list