Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ... #endif 

Thanks very much!

like image 903
KL. Avatar asked Jan 08 '10 17:01

KL.


People also ask

What happens if I import the same module twice Python?

Nothing, if a module has already been imported, it's not loaded again.

What will happen if a feature module is imported multiple times?

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.

Can you double import in Python?

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.

How many times can we import any module in an interpreter session?

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.


2 Answers

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 
like image 69
Noufal Ibrahim Avatar answered Oct 02 '22 07:10

Noufal Ibrahim


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

like image 23
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 06:10

Ignacio Vazquez-Abrams