Does python optimize modules when they are imported multiple times?

Python modules could be considered as singletons… no matter how many times you import them they get initialized only once, so it’s better to do:

import MyLib
import ReallyBigLib

Relevant documentation on the import statement:

https://docs.python.org/2/reference/simple_stmts.html#the-import-statement

Once the name of the module is known (unless otherwise specified, the term “module” will refer to both packages and modules), searching for the module or package can begin. The first place checked is sys.modules, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import.

The imported modules are cached in sys.modules:

This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.

Leave a Comment