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!
Nothing, if a module has already been imported, it's not loaded again.
If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used. If a module is imported multiple times, but with the same specifier (i.e. path), the JavaScript specification guarantees that you'll receive the same module instance.
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.
For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it's just one module you want to test interactively, use importlib.
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
Imports are cached, and only run once. Additional imports only cost the lookup time in sys.modules
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With