import statement within a function

Peter Hansen peter at engcorp.com
Sat Feb 3 09:34:16 EST 2001


Tomasz Lisowski wrote:
> 
> "Peter Hansen" <peter at engcorp.com>:
> > The one you highlight, "performance", should probably be
> > considered the _least_ important of the points Fredrik raised.
> 
> That depends, on what the given function does, and how often it is called,
> of course.
> 
> > The last one, which implies improved maintainability, is
> > far more important (IMHO) ...
> 
> Moreover, it is a matter of taste, whether I put the import statement at the
> beginning of the file, even if the given module is imported only by one
> function, since this function will be eventually called (there was surely a
> reason for writing it, wasn't it?). Therefore I have asked Frederik about
> REAL advantages, that could persuade me to put import statements within a
> function. Performance, IMHO, is one of them.

We're definitely talking from different backgrounds, but there's
room for that.  In my world, performance is NEVER an issue ahead
of time, but getting things to work is.  Performance becomes an
issue only when it is insufficient for the purpose, and in 
that case it would be good to know that by putting the import
inside a "hot spot" function, its performance may be improved.
After profiling and seeing unacceptable performance.

On the other hand, for me maintainability is ALWAYS an issue
ahead of time and throughout the life of the code.  To make
the code more maintainable, it may be necessary to comment
why a module is imported (if it is imported at the top far
away from the function using it).  By placing the import
within the single function which uses it, the code becomes
effectively self-documenting and needs no additional comment
regarding the module.  I can always 'grep' the code to find
all import statements, if that is necessary (which it rarely 
is, for me).

So to me this is very much a REAL advantage, but I can see
you have a different (and perfectly valid, for you) perspective.

:)



More information about the Python-list mailing list