Quote:
Originally Posted by Dietrich
I usually import all the needed modules in the beginning of my program. I keep seeing code that imports modules within a function, wouldn't that be bad? I assume that the module will be imported every time the function is called.
|
Modules are cached in memory, so they are only ever imported once. This can be tested via the following code:
def foo():
import string
string.test = "Hello"
print string.test
def bar():
import string
print string.test
foo()
bar()
However, even though modules are cached, there's still some overhead in searching the cache for the module. So although it doesn't make much difference, it still results in slight performance degradation