views:

141

answers:

2

Hello,

When writing python modules, is there a way to prevent it being imported twice by the client codes? Just like the c/c++ header files do:

#ifndef XXX
#define XXX
...
#endif

Thanks very much!

+2  A: 

Imports are cached, and only run once. Additional imports only cost the lookup time in sys.modules.

Ignacio Vazquez-Abrams
+7  A: 

Python modules aren't imported multiple times. Just running import two times will not reload the module. If you want it to be reloaded, you have to use the reload statement. Here's a demo

foo.py is a module with the single line

print "I am being imported"

And here is a screen transcript of multiple import attempts.

   >>> import foo
   Hello, I'm being imported
   >>> import foo # Will not print the statement
   >>> reload(foo) # Will print it again
   Hello, I'm being imported
Noufal Ibrahim
Do note that `reload()` won't fix up any references to the old module, so is not actually all that useful.
Ignacio Vazquez-Abrams
That's an important point. Thanks.
Noufal Ibrahim
References: http://docs.python.org/tutorial/modules.html#more-on-modules. http://docs.python.org/reference/simple_stmts.html#the-import-statement
S.Lott
Remember as well of performing imports outside of threads whenever possible, although that rarely causes problems.
Alan Franzoni