How does Python's module import system avoid re-executing a module multiple times when imported from different places?
Short answer
Python caches every imported module in sys.modules keyed by its fully qualified name.
Advertisement
AModel answer
Python caches every imported module in sys.modules keyed by its fully qualified name. When any code does `import foo`, Python checks sys.modules first; if already present, it reuses the cached module object instead of re-running foo.py, ensuring module-level code executes exactly once per process and all importers share the same module object (and its state).
import sys
import json
print('json' in sys.modules) # True after first import
# Subsequent imports reuse the cached module -- no re-execution
import json as json2
print(json is json2) # True, same objectReal-world example
A configuration module that loads settings once at import time relies on this caching -- every part of the application importing `config` gets the same already-initialized settings object, not a fresh reload.
Likely follow-ups
- How do you force a module to reload with importlib.reload()?
- Why can module-level side effects be risky given this caching?
Related topics