Python Import Machinery & sys.modules Cache
1Concept
When `import x` is invoked, Python checks `sys.modules`. If cached, the module is returned immediately. Otherwise, Python iterates through `sys.meta_path` finders, locates the file, creates a module spec, allocates the module object, and executes its bytecode in a new namespace.
2Architecture Diagram
import my_module ---> [ Found in sys.modules? ] --Yes--> Return cached instance
| No
Find Spec -> Load Bytecode -> Cache -> Return3Code Example
Python 3.12
import sys
import math
print(f"Is math cached in sys.modules: {'math' in sys.modules}")
print(f"Math module object: {sys.modules['math']}")
print(f"Total modules loaded in runtime: {len(sys.modules)}")4Expected Output
Is math cached in sys.modules: True Math module object: <module 'math' (built-in)> Total modules loaded in runtime: 78
5Key Takeaways
- ✓Modules are singletons; importing the same module across 100 files executes its top-level code once.
- ✓Deleting an entry from `sys.modules` forces Python to re-import it on the next call.
- ✓Circular imports fail when module A needs an attribute from module B before B completes initialization.