Best practices with import?

David Bolen db3l at fitlinxx.com
Mon Jul 30 16:56:36 EDT 2001


Peter Hansen <peter at engcorp.com> writes:

> Possible reasons to import in a function: 
> 
>  1. Readability: if the import is needed in only one
>     function and that's very unlikely ever to change,
>     it might be clearer and cleaner to put it there only.
> 
>  2. Startup time: if you don't have the import outside
>     of the function definitions, it will not execute
>     when your module is first imported by another, but
>     only when one of the functions is called.  This
>     delays the overhead of the import (or avoids it
>     if the functions might never be called).

One thing to point out is that the "might never be called" part may be
more than just convenience, if the import that is being done is
platform-specific.  In such a case, putting the import at the top of
the screen could prevent it from loading at all (without a dedicated
try/except block around it), while placing it inline in the platform
specific code is a bit more straight-forward.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list