Best practices with import?

Peter Hansen peter at engcorp.com
Sun Jul 29 00:55:23 EDT 2001


chris liechti wrote:
> 
> Erik Max Francis <max at alcyone.com> wrote:
> >      def main():
> >          import sys # here's the only place that sys gets used
> >          lines = sys.readlines()
> >          # do something with lines ...
> >
> > I'm really not sure what the value would be in deleting the module after
> > you're through with it, except perhaps to clean up namespaces, which I
> > wouldn't think would be useful if, say, it were defined in the scope of
> > a function.
> 
> i think the module gets deleted anyway because its imported into the local
> namespace of the function and that gets deleted after the function returns.
> 
> there is a performance argument against "import"ing in functions:
> if this fu is called in a loop the module gets imported and deleted every
> time. importing it at top level doesn't need that and hence the loop runs
> faster.

It is practically impossible actually to delete a module.  The module
is only ever imported _once_, and subsequent import statements just
recreate a reference to the same module.

>>> import sys,os
>>> os
<module 'os' from 'c:\a\python\lib\os.pyc'>
>>> del os
>>> sys.modules['os']
<module 'os' from 'c:\a\python\lib\os.pyc'>

The only cost then of having import in a function is the cost of a
dictionary lookup (and perhaps some trivial other overhead)...not much.

There is at least one situation where import in a function is very
useful, and that is to delay execution of the import.  If the first
module is imported by another, and all of its import statements are
at the top, each import executes at that time, slowing down loading
of the first module.  If one of the imported modules is needed only
in one of the functions, which may or may not be called, putting 
the import statement in the function will postpone (perhaps avoid)
the import and improve responsiveness.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list