Why import only at module level?

Peter Hansen peter at engcorp.com
Thu Feb 19 17:59:14 EST 2004


François Pinard wrote:
> 
> [Peter Hansen]
> > Maintainability.  It's also well understood that there are potential
> > benefits to the approach you show above, late-loading of code being
> > one of them (which can improve startup time for certain apps), but
> > as maintainability should almost always be the primary consideration,
> > the standard advice is to put stuff together at the top where it's
> > clear to maintainers which modules are used in the code (in other
> > words, what a given module is coupled to).
> 
> I never understood this "standard advice", nor how it is related to
> maintainability.  What makes a module significantly more maintainable
> by merely grouping `import' statements at the beginning?  What is it so
> crucial to know that the `re' module is used, or not, in a program?  It
> looks like a tiny detail to me.

"re" is not a good example of the above, though there might also be
very good but different reasons to import re at the top.  Often it 
is used in several different places, and that would mean duplication
(and a tiny waste of time) if you always imported it at the beginning
of each method, or even just before it was used.

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.  

More coupling means less maintainability.

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.

> If within a `def', I will often use a module which I do not use
> elsewhere in a program, there is no reason to make it global.  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.

-Peter



More information about the Python-list mailing list