Importing again and again
Laszlo Nagy
gandalf at designaproduct.biz
Thu Jun 8 16:55:20 EDT 2006
abcd írta:
> 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?
Just once. Try this:
bar.py:
print "I have been imported"
def printStuff():
print "printStuff was called"
foo.py:
def foo():
import bar
bar.printStuff()
foo()
foo()
foo()
The result is:
I have been imported
printStuff was called
printStuff was called
printStuff was called
If you really need to reimport the module, you can do this:
foo.py:
import bar
def foo():
global bar
bar = reload(bar)
bar.printStuff()
foo()
foo()
foo()
The result is:
I have been imported
I have been imported
printStuff was called
I have been imported
printStuff was called
I have been imported
printStuff was called
> Is this a big performance hit?
>
It depends on the size of your 'bar.py' module, and also it depends on
how often you need to change/reload while your program is running.
Best,
Laszlo
More information about the Python-list
mailing list