One class per file?

Roy Smith roy at panix.com
Mon Sep 29 09:56:19 EDT 2008


In article 
<a932e44b-3566-4c0f-8b63-2dce0a82946b at 34g2000hsh.googlegroups.com>,
 HCB <hypercaffeinatedbiped at gmail.com> wrote:

> Hello:
> 
> The book "Code Complete" recommends that you put only one class in a
> source file, which seems a bit extreme for me. It seems that many
> classes are small, so that putting several of them in a file seems
> reasonable. I noticed that the decimal.py module in the standard
> library has several classes, all of which of course revolve around the
> "decimal" topic. Perhaps a better rule of thumb is "one idea per
> file." I checked the Python style guide and there seems to be no
> mention of this topic. I know this is an elementary question, but what
> is the Python way of doing this?
> 
> Thanks for your time.
> HCB

Steve McConnell writes a lot of good stuff.  Like most people who write a 
lot of good stuff, not everything he writes should be taken as gospel.  
With that in mind...

Consider this.  You're slogging through some code in a large project trying 
to debug a problem when you come upon the line (in pseudo-code):

   foo = SomeClass::SomeFunction(bar)

You want to go look at the source for SomeClass.  What file do you open to 
find it?  If you follow the "one class per file" rule, the answer is easy; 
it's in SomeClass.xxx!

That being said, the "one class per file" rule is a means to an end.  If 
your code is written in such a way that it's easy to figure out where the 
source for a given class/function/whatever is, then you've done the right 
thing.  The specifics of how you do that depend on the language you're 
using.

In Python (as other posters have pointed out), modules give you a good way 
to group logical collections of classes (etc).  If you see in some code:

   foo = some_module.SomeClass.SomeFunction(bar)

you should instantly know that the source code is in some_module.py.  
Perhaps one way to look at this is that Python automatically follows the 
"one class per file" rule, except that "class" is crossed out and "module" 
written in with crayon.

On the other hand, if you prefer self-abuse, Python gives you plenty of 
ways to do that.  If you preface all your source files with:

from some_module import *
from some_other_module import *
from yet_a_third_module import *
from another_module import *

and then see

   foo = SomeClass.SomeFunction(bar)

you're right back to having no clue what file to open to find the source 
for SomeClass.  Global namespace is sacred; treat it with respect!



More information about the Python-list mailing list