Importing again and again

Steve Holden steve at
Fri Jun 9 09:00:19 CEST 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.

Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd
Love me, love my blog
Recent Ramblings

More information about the Python-list mailing list