best practices - how to organize classes

Roy Smith roy at panix.com
Tue Nov 25 17:36:48 CET 2003


In article <59e5b87.0311250821.629674f0 at posting.google.com>,
 mirandacascade at yahoo.com (Miranda Evans) wrote:

> Seeking reference material (a url, a book, an article) that offers
> advice and guidelines for organizing classes within files.
> 
> For example, assume two classes:
> 1) SuperABC - a superclass
> 2) InheritorABC - a class that inherits from SuperABC
> 
> I can think of two ways of organizing these classes within files:
> 1) One class per file:
> - the file SuperABCClass.py contains the source code for the class
> SuperABC
> - The file InheritorABCClass.py contains the source code for the class
> InheritorABC
> - InheritorABC imports SuperABCClass
> 2) Grouping classes into one .py file:
> - the file GroupedABCClasses.py contains the source code for the class
> SuperABC and the source code for the class InheritorABC
> 
> Seeking reference material that might answer the questions:
> When does it make sense to employ the one-class-per-file technique?
> When does it make sense to group classes into one .py file?
> What are the tradeoffs of using one-class-per-file technique vs the
> grouping classes into a single file technique?

I don't think there is any single correct answer.  It's more of a 
judgement call.

In general, I'll put more than one class in a single source file only if 
they formed a logically self-contained unit of inter-dependant classes.  
Kind of like an inner class in C++.

For example, let's say I was building a RedBlackTree class, and I needed 
a TreeNode class to store the individual nodes.  I would probably put 
both classes in one file.

If I needed to define exception classes, they would certainly go in the 
same source file as the class which generated those exceptions.




More information about the Python-list mailing list