Importing again and again

Steve Holden steve at holdenweb.com
Fri Jun 9 03:00:19 EDT 2006


abcd wrote:
> If I have code which imports a module over and over again...say each
> time a function is called, does that cause Python to actually re-import
> it...or will it skip it once the module has been imported??
> 
> for example:
> 
> def foo():
>     import bar
>     bar.printStuff()
> 
> foo()
> foo()
> foo()
> foo()
> 
> ...will that re-import bar 4 times...or just import it once?  is this a
> big performance hit?
> 
> thanks
> 
To address the performance question, by the way, the first thing that 
the import process does is look in sys.modules to see whether the module 
has already been imported. If so then it uses the module referenced by 
sys.modules, so the overhead is pretty small (dicts being quite fast 
generally speaking).

So your code is a reasonable way to defer the import of bar until the 
function is called, which is why I presumed you coded it that way.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list