Python Execution Model, CPython Bytecode & __name__ == '__main__'
1Concept
Python source files (.py) are parsed into an Abstract Syntax Tree (AST), compiled into CPython bytecode (.pyc in __pycache__), and executed by the CPython Virtual Machine. The idiom if __name__ == '__main__': checks if the script is run directly or imported as a module.
2Architecture Diagram
[script.py] ──► [AST Parser] ──► [Bytecode (.pyc)] ──► [CPython Virtual Machine (Eval Loop)]
3Code Example
Stage 0 Language Foundations
import sys
import platform
def main():
print("=== Python 3.12 Runtime Engine ===")
print(f"Python Version: {platform.python_version()}")
print(f"Implementation: {platform.python_implementation()}")
print(f"Recursion Limit: {sys.getrecursionlimit()}")
if __name__ == "__main__":
main()4Expected Output
=== Python 3.12 Runtime Engine === Python Version: 3.12.2 Implementation: CPython Recursion Limit: 1000
5Key Takeaways
- ✓if __name__ == '__main__' prevents code from executing automatically on import.
- ✓CPython compiles bytecode to __pycache__ to speed up subsequent load times.
- ✓Python uses dynamic typing evaluated at runtime.