Why import only at module level?

François Pinard pinard at iro.umontreal.ca
Fri Feb 20 00:42:17 CET 2004

[Peter Hansen]
> François Pinard wrote:

> A better example is application-specific modules.  "Hiding" those down
> in the individual methods that use them makes it much more difficult
> to see the coupling between modules.

Agreed indeed, the coupling between modules is less explicit then.

> More coupling means less maintainability.

On the other hand, the location of `import' has no effect on the amount
of coupling.

> 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.

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!

> > Global variables should be avoided on the average, and moreover,
> > Python is faster at accessing a local than a global.

> As you probably know, I almost never put performance anywhere near the
> level I put other considerations, so if we still differ on this matter,
> perhaps it's because of different values.

Performance is not to be a primary concern on the average, quite
agreed!  Still, a few simple habits are easily acquired that yield
faster programs on average, which happily coincide with good programming
practices.  I consider this coincidence as a reason to rejoice! :-)

François Pinard   http://www.iro.umontreal.ca/~pinard

More information about the Python-list mailing list