When you import a module, then reimport it again, will it get reimported/overwritten, or skipped? When you import module "a" and "b", but also have module "b" imported in module "a", what happens? Is it safe to do this? For example if that module "b" has a class instantiated in it, will you end up instantiating it twice?
import loads the matching .py, .pyc or .pyo file, creates a module object, and stores it with its fully qualified ("dotted") name in the sys.modules dictionary. If a second import finds the module to import in this dictionary, it will return it without loading the file again.
To answer your questions:
When you import a module, then reimport it again, will it get reimported/overwritten, or skipped?
It will get skipped. To explicitely re-import a module, use the reload() built-in function.
When you import module "a" and "b", but also have module "b" imported in module "a", what happens?
import a will load a from a.py[c], import b will return the module sys.modules['b'] already loaded by a.
Is it safe to do this?
Yes, absolutely.
For example if that module "b" has a class instantiated in it, will you end up instantiating it twice?
Nope.
The module will only be instantiated once. It is safe to import the same module in multiple other modules. If there is a class instance (object) that is created in the module itself, the very same object will be accessed from all modules that import it.
You can, if you like, have a look at all imported modules:
import sys
print sys.modules
sys.modules is dictionary which maps module names the module objects. The first thing the import statement does is looking in sys.modules, if it cannot find the module there, it will be instantiated, and added to sys.modules for future imports.
See this page for more details: http://effbot.org/zone/import-confusion.htm (see "What Does Python Do to Import a Module?")
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