Where to import modules?

Peter Hansen peter at engcorp.com
Fri Sep 26 16:11:43 CEST 2003


JCM wrote:
> 
> Peter Hansen <peter at engcorp.com> wrote:
> ...
> 
> > Basically doing this is an optimization, and you shouldn't be optimizing
> > before the program is working, and you shouldn't be optimizing without
> > a real need for it.  (That is, just because it's a little faster doesn't
> > mean it's worth doing.)
> 
> Aside from being an optimization, it's also good for documentation.
> If you see an import at the top of a file it might not be immediately
> clear how or why the module is being used.  It's similar reasoning to
> why you might define variables in the narrowest scope posible.

I'm not sure it's necessarily any clearer when you put the import 
somewhere down in the file, effectively hiding it from casual viewing.

At the top, it's at least clear that the module *is* imported.  If
you care how it's used, a simple search for "module." will show all
the places where it's used.

In the middle of code somewhere, you can clearly see how it's being
used only if you're actually looking at that exact line.

John Roth has the right approach: whatever you do, a comment up 
at the top with the others would go a long way towards appeasing
any concerns about maintainability.  Unfortunately, that does mean
there's isolated duplication (the import, somewhere below, plus the 
comment at the top) and therefore another, though perhaps lesser, 
maintainability problem.

-Peter




More information about the Python-list mailing list