Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   Import a Module (http://www.programmingforums.org/showthread.php?t=12277)

Dietrich Dec 28th, 2006 12:25 PM

Import a Module
 
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.

BinarySurfer Dec 28th, 2006 12:52 PM

I've done it before without any problems, though I would avoid importing the randomizer in a function. The module would be loaded at the beginning of the function (or where ever) and dropped at the end, so it's I think it's okey. I don't recommend doing it that way because it hurts performance if that function is used often. I would do it in a function that's not used often, otherwise I would import it at the beginning of the code like usual.

Arevos Dec 28th, 2006 1:41 PM

Quote:

Originally Posted by Dietrich (Post 121827)
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:
:

  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

titaniumdecoy Dec 28th, 2006 5:10 PM

Quote:

Originally Posted by Arevos (Post 121832)
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

Wouldn't the cache have to be searched either way?

Game_Ender Dec 29th, 2006 2:21 AM

It will only get searched once you import the module at file scope. It will be searched every time you run the function if you import inside the function.

Arevos Dec 29th, 2006 5:47 AM

Quote:

Originally Posted by titaniumdecoy (Post 121837)
Wouldn't the cache have to be searched either way?

As I understand it, if it's already imported, only the namespace must be searched for the module name. If it's imported in the middle of the function, first the module cache has to be searched (in order to import the module into the current namespace), and then the namespace.


All times are GMT -5. The time now is 11:18 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC