Why import only at module level?

Peter Hansen peter at engcorp.com
Thu Feb 19 19:07:20 EST 2004


François Pinard wrote:
> 
> [Peter Hansen]
> > More coupling means less maintainability.
> 
> On the other hand, the location of `import' has no effect on the amount
> of coupling.

I think I can make a good argument that it does.  Try this on for size:
if the import of module B is in several methods of module A, then each of 
those methods is directly coupled to module B.  You've got several 
instances of coupling.  Now move the duplicate imports up to the top
of module A.  Each method is now coupled only to module A, which of
course all methods in that module are, but only module A has any 
coupling to module B.

When I analyze coupling, I consider the links to have both strength 
and quantity.  Generally a reduction in quantity is just as useful
as a reduction in strength of coupling, IME.

> > Second reason: if you put your import, which you use in only one
> > place, locally in the method where it's used, then modify the code so
> > that another method also uses the module, you will end up with two
> > imports.  More duplication means less maintainability.
> 
> Maybe not.  I may have many functions each having a local counter, and
> despite all the duplication, using a single global counter instead would
> not imply more maintainability.  Locality (of definition and use) is
> often best for maintainability, even if it means random duplication.

Unfortunately you lost me with the example.  I can't see the connection
between having separate local counters and a single global counter, 
since presumably the logic requires either one or the other.  (I trust
you had a valid point but I missed it, sorry.)

> There is no definitive rule about what is good or bad, and this is where
> good taste comes in, which turns all this program writing into an art!

Very true of course, as with all design.

-Peter



More information about the Python-list mailing list