1. Module Import Mechanics and sys.path
How CPython Locates and Caches Modules
- When you execute `import math`, Python searches directories listed in `sys.path`.
- Once found, Python compiles the file to bytecode (.pyc in __pycache__), executes the top-level code, and caches the module in `sys.modules`.
- Subsequent imports of the same module retrieve the cached reference without re-executing.
import sys
print("Current Python sys.path entries:", len(sys.path))
import math as m
print("Square root of 25:", m.sqrt(25))
💡 Key Takeaway: Python caches loaded modules in sys.modules, executing module code only once per process.