About one class/function per module

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Nov 3 00:17:38 EST 2009


On Mon, 02 Nov 2009 07:24:59 -0600, Peng Yu wrote:

> Suppose I have class A and class B in a file, I can not easily figure
> out which class depends on which class by a simple script. 

How about looking at the classes?

>>> class A:
...     pass
...
>>> class B(A):
...     pass
...
>>>
>>> B.__bases__
(<class __main__.A at 0xb7caccbc>,)

Classes know their own dependencies. Just ask them:

import module
for superclass in module.A.__bases__:
    print superclass, "is a dependency for class A"



> However, if
> they are in two separate files, for example B depends on A, then I will
> have 'import A' in file B. This dependency can be easily figured out by
> a script.


If they are in the same file, you can just look at the class definition:

class B(A):

And now you know with 100% accuracy that B depends on A, instead of 
guessing that just because you import a module, that means you must have 
used a class from that module.


> The following scenario also demonstrate why the maintenance cost is
> lower with one class/function per file, because it decouples
> dependences. Let's suppose class A and B are in the same file. Now I'm
> changing class B. But while I'm changing class B, I just realize that I
> have to change A. But since the change in B is half way done
> (syntactical not correct), I will not be able to run the test case for
> A, because the test case import the file that has class B. In contrast,
> if A and B are in different files, even if B is half way done, I can
> still run test case for A.

Assuming A and B are independent, or that B depends on A but not the 
opposite, failing tests for B won't cause tests for A to fail. This 
doesn't change whether A and B are in the same file or not.

The one exception to this is syntax errors. But if your project contains 
syntax errors, why are you trying to run test suites? 



-- 
Steven



More information about the Python-list mailing list