CPython Internals
How the reference Python implementation runs your code — compilation to bytecode, the dis module, the evaluation loop and frames, PyObject and reference counting, small-object caches, the specialising adaptive interpreter, the JIT, and alternative implementations.
"Python" is a language specification; CPython is the reference implementation, written in C, that almost everyone uses. Knowing how it executes code explains Python's performance profile, its memory behaviour, and why some idioms are faster than others.
From source to execution
- The tokenizer and PEG parser turn source text into an abstract syntax tree (
ast.parseexposes it). - The compiler builds a symbol table (which names are local, global, free), then emits bytecode into code objects — one per module, function, class body and comprehension. It also does simple optimisations like constant folding.
- Compiled bytecode is cached in
__pycache__/*.pycfiles (keyed by the interpreter version) so imports skip recompiling. - The evaluation loop (
_PyEval_EvalFrameDefaultinceval.c) executes the bytecode, one instruction at a time.
Bytecode and the dis module
CPython's VM is a stack machine, like the JVM (JVM architecture):
import dis
def add_tax(price, rate=0.2):
return price * (1 + rate)
dis.dis(add_tax) RESUME 0
LOAD_FAST 0 (price)
LOAD_CONST 1 (1)
LOAD_FAST 1 (rate)
BINARY_OP 0 (+)
BINARY_OP 5 (*)
RETURN_VALUEEach instruction manipulates the frame's value stack: push price, push 1, push rate, pop two and push their sum, pop two and push the product, return the top. (Exact opcodes vary between versions.)
A function's code object holds the bytecode (co_code), constants (co_consts), local variable names (co_varnames), and more:
add_tax.__code__.co_varnames # ('price', 'rate')
add_tax.__code__.co_consts # (None, 1)Frames
Each function call creates a frame: its local variables (stored in a fixed array — which is why local variable access via LOAD_FAST is faster than globals looked up in a dict), the value stack, the instruction pointer and a link to the calling frame. Since 3.11, frames are allocated in a contiguous per-thread stack, and Python-to-Python calls don't recurse in C, making calls much cheaper.
Everything is a PyObject
Every Python value is a C struct that begins with a common header:
typedef struct _object {
Py_ssize_t ob_refcnt; // reference count
PyTypeObject *ob_type; // pointer to the type: int, list, your class…
} PyObject;The type object holds function pointers for operations (tp_hash, tp_richcompare, nb_add…). When you write a + b, the interpreter calls a's type's add slot — dunder methods defined in Python classes are wired into these slots (OOP & the data model).
This uniformity has costs: a Python int is a heap object of at least 28 bytes; a list of a million ints holds a million pointers to separate objects. That's why NumPy arrays (one contiguous buffer of raw numbers) are so much smaller and faster.
import sys
sys.getsizeof(1) # 28
sys.getsizeof(2**100) # 40 — ints grow as needed (arbitrary precision)
sys.getsizeof([]) # 56 (plus 8 bytes per slot)Memory management
- Reference counting is the primary mechanism: every new reference increments
ob_refcnt, every dropped reference decrements it, and the object is freed immediately when it hits zero. Deterministic and simple, but it costs on every assignment and can't free cycles. - A cyclic garbage collector periodically finds reference cycles among container objects and frees them.
- pymalloc, a small-object allocator with arenas and size-class pools, makes allocating many small objects fast.
Details in Memory & the GIL.
Caches and interning
a = 256; b = 256
a is b # True — integers -5..256 are pre-allocated singletons
a = 257; b = 257
a is b # may be False (implementation detail!)
s1 = "hello"; s2 = "hello"
s1 is s2 # True — identifier-like string literals are internedNever rely on is for value comparison — these caches are optimisations, not guarantees.
The specialising adaptive interpreter (3.11+)
The "Faster CPython" project made 3.11 about 25% faster on average. The key idea: quickening. After an instruction runs a few times, CPython replaces it in place with a specialised version for the types it has seen:
| Generic instruction | Specialised variants |
|---|---|
BINARY_OP (+) | BINARY_OP_ADD_INT, BINARY_OP_ADD_FLOAT, BINARY_OP_ADD_UNICODE |
LOAD_ATTR | LOAD_ATTR_INSTANCE_VALUE, LOAD_ATTR_SLOT, LOAD_ATTR_MODULE, LOAD_ATTR_METHOD_… |
LOAD_GLOBAL | LOAD_GLOBAL_MODULE, LOAD_GLOBAL_BUILTIN (cached by dict version) |
CALL | CALL_PY_EXACT_ARGS, CALL_BUILTIN_FAST, CALL_LEN … |
Each specialised instruction checks a cheap guard (is it still an int?) and de-specialises if the guard fails. It's the inline-cache idea from V8 and the JVM, applied inside an interpreter. You can see it with dis.dis(fn, adaptive=True) after running a function many times.
The experimental JIT (3.13+)
CPython 3.13 added an optional copy-and-patch JIT: hot traces of specialised micro-ops are stitched together from pre-compiled machine-code templates. It's built with --enable-experimental-jit and still maturing; gains so far are modest.
Why Python is "slow" — and what to do
| Cost | Why |
|---|---|
| Dynamic dispatch on every operation | a + b must check types at runtime |
| Boxed objects | Numbers are heap objects with headers |
| Dict-based namespaces | Global and attribute lookups (though heavily cached now) |
| Interpretation overhead | A C loop dispatching each bytecode |
| The GIL | One thread executes bytecode at a time (until free-threaded builds) |
Practical speed-ups:
- Use built-ins and the standard library (
sum,sorted,str.join,collections) — they run in C. - Push numeric work into NumPy/pandas/Polars (vectorised C/Rust loops).
- Cache attribute lookups in hot loops; prefer local variables.
- Profile with
cProfile,py-spyorscalenebefore optimising. - Compile hot spots: Cython, mypyc, Numba (JIT for numeric code), or write a Rust extension with PyO3.
- Try PyPy — a tracing-JIT implementation often 4–10× faster for pure-Python code.
Other implementations
| Implementation | Notes |
|---|---|
| CPython | Reference; C extensions ecosystem |
| PyPy | Tracing JIT, often much faster; C-extension compatibility via an emulation layer |
| MicroPython / CircuitPython | For microcontrollers |
| GraalPy | On GraalVM, interop with Java |
| Pyodide | CPython compiled to WebAssembly, runs in browsers |
- CPython parses to an AST, compiles to bytecode in code objects (cached in .pyc), and runs it in a stack-based eval loop.
- Use dis to see bytecode; locals are array slots, so they're faster than globals.
- Every value is a PyObject with a refcount and type pointer — flexible but memory-heavy.
- Small ints and some strings are cached; never rely on is for equality.
- 3.11+ specialises instructions in place based on observed types; 3.13 adds an experimental JIT.
- For speed: built-ins, NumPy, profiling, Cython/Numba/PyO3, or PyPy.