Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python's "import" work internally?

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?


2 Answers

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.

like image 104
Ferdinand Beyer Avatar answered Jan 28 '26 13:01

Ferdinand Beyer


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?")

like image 43
andreaspelme Avatar answered Jan 28 '26 13:01

andreaspelme