Importing again and again
steve at holdenweb.com
Fri Jun 9 09:00:19 CEST 2006
> 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
> ...will that re-import bar 4 times...or just import it once? is this a
> big performance hit?
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
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 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