Where to import modules?

Peter Hansen peter at engcorp.com
Fri Sep 26 08:55:54 EDT 2003


Andreas Neudecker wrote:
> 
> I have a "style" question: Sometimes, modules will only be used in a
> particular, optional, part of a program (function, class), that will not
> always be used when the application is run. So I think it is better to
> import them only there, not on the top of the file (together with the
> other imports). Is that okay, or are there good reasons for not doing so?

There are not *strong* reasons for avoiding the delayed-import style,
although clearly maintainability can be affected.  It makes it somewhat
harder for a maintainer to see that a given module is used at all.

I would not bother putting imports that are rarely used in only the
functions which need them *unless* I had a really large module which
took a long time to import and I was actually having problems with 
startup time for the application.

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

-Peter




More information about the Python-list mailing list