KL. KL. - 1 year ago 82
Python Question

How to prevent a module from being imported twice?

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

Thanks very much!

Answer Source

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 am being imported
   >>> import foo # Will not print the statement
   >>> reload(foo) # Will print it again
   Hello, I am being imported
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download