Thread: Import a Module
View Single Post
Old Dec 28th, 2006, 1:41 PM   #3
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by Dietrich View Post
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:
python Syntax (Toggle Plain Text)
  1. def foo():
  2. import string
  3. string.test = "Hello"
  4. print string.test
  5.  
  6. def bar():
  7. import string
  8. print string.test
  9.  
  10. foo()
  11. 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
Arevos is offline   Reply With Quote