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!
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!
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 demofoo.py
is a module with the single lineAnd here is a screen transcript of multiple import attempts.
Imports are cached, and only run once. Additional imports only cost the lookup time in
sys.modules
.As specified in other answers, Python generally doesn't reload a module when encountering a second import statement for it. Instead, it returns its cached version from
sys.modules
without executing any of its code.However there are several pitfalls worth noting:
Importing the main module as an ordinary module effectively creates two instances of the same module under different names.
This occurs because during program startup the main module is set up with the name
__main__
. Thus, when importing it as an ordinary module, Python doesn't detect it insys.modules
and imports it again, but with its proper name the second time around.Consider the file /tmp/a.py with the following content:
Another file /tmp/b.py has a single import statement for a.py (
import a
).Executing /tmp/a.py results in the following output:
Therefore, it is best to keep the main module fairly minimal and export most of its functionality to an external module, as advised here.
This answer specifies two more possible scenarios:
sys.path
leading to the same module.