How Python source code (.py) is tokenized, parsed into an Abstract Syntax Tree (AST), compiled into bytecode (.pyc), and executed by the CPython virtual evaluation loop.
“Python is an interpreted, bytecode-compiled language. CPython tokenizes source, constructs an AST, compiles bytecode, and executes opcodes sequentially in ceval.c.”
Developers author human-readable Python script adhering to PEP 8 idioms and Python 3.12+ syntax rules.
def compute_sum(a: int, b: int) -> int:
result = a + b
return result
print(compute_sum(40, 2))The compiler constructs a PyCodeObject containing bytecode instructions, constant tuples (co_consts), and local variable names (co_varnames).
LOAD_FAST pushes local variable 'n' onto the CPython execution frame's value stack twice.
BINARY_OP pops the top two values, multiplies them via the PyNumber_Multiply C API, and pushes the product.
RETURN_VALUE pops the product from the stack and hands it back to the caller frame.
# Exploring Python Bytecode via the standard 'dis' disassembler module
import dis
def compute_square(n: int) -> int:
result = n * n
return result
print("=== Python Function Disassembly ===")
dis.dis(compute_square)=== Python Function Disassembly ===
5 0 RESUME 0
6 2 LOAD_FAST 0 (n)
4 LOAD_FAST 0 (n)
6 BINARY_OP 5 (*)
10 STORE_FAST 1 (result)
7 12 LOAD_FAST 1 (result)
14 RETURN_VALUEPython is both. Source code is first compiled into intermediate bytecode (.pyc), which is then interpreted by the CPython virtual machine execution loop (ceval.c). Implementations like PyPy use JIT (Just-In-Time) compilation to emit native machine code at runtime.
Python 3.9 replaced the legacy LL(1) parser with a Parsing Expression Grammar (PEG) parser. PEG allows arbitrary lookahead, eliminating grammatical ambiguities and enabling modern syntax features like structural pattern matching (match/case).