I've been wondering this for a while: Is it guaranteed to be safe to import a module multiple times? Of course, if the module performs operating systems things like write to files or something, then probably not, but for the majority of simple modules, is it safe to simply perform imports willy-nilly? Is there a convention that governs the global state of a module?
The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.
So each module is imported only one time. To better understand import mechanics I would suggest to create toy example. So import really happens only once. You can adjust this toy example to check cases that are interesting to you.
In fact, Python only loads the module when it is imported in the first file and all subsequent files simply set the name to refer to the already loaded module. While it is possible to override this behavior so that each file has its own copy of the module, it is generally not recommended.
Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names, if placed at the top level of a module (outside any functions or classes), are added to the module's global namespace.
Yes, you can import module
as many times as you want in one Python program, no matter what module it is. Every subsequent import
after the first accesses the cached module instead of re-evaluating it.
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