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.

Advanced 4 min readLesson 6 of 10

"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

source .pytokenizer + parserPEG grammarASTcompiler→ code objectseval loopceval.c
  1. The tokenizer and PEG parser turn source text into an abstract syntax tree (ast.parse exposes it).
  2. 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.
  3. Compiled bytecode is cached in __pycache__/*.pyc files (keyed by the interpreter version) so imports skip recompiling.
  4. The evaluation loop (_PyEval_EvalFrameDefault in ceval.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):

Python
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_VALUE

Each 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:

Python
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:

C
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.

Python
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

Python
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 interned

Never 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 instructionSpecialised variants
BINARY_OP (+)BINARY_OP_ADD_INT, BINARY_OP_ADD_FLOAT, BINARY_OP_ADD_UNICODE
LOAD_ATTRLOAD_ATTR_INSTANCE_VALUE, LOAD_ATTR_SLOT, LOAD_ATTR_MODULE, LOAD_ATTR_METHOD_…
LOAD_GLOBALLOAD_GLOBAL_MODULE, LOAD_GLOBAL_BUILTIN (cached by dict version)
CALLCALL_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

CostWhy
Dynamic dispatch on every operationa + b must check types at runtime
Boxed objectsNumbers are heap objects with headers
Dict-based namespacesGlobal and attribute lookups (though heavily cached now)
Interpretation overheadA C loop dispatching each bytecode
The GILOne 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-spy or scalene before 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

ImplementationNotes
CPythonReference; C extensions ecosystem
PyPyTracing JIT, often much faster; C-extension compatibility via an emulation layer
MicroPython / CircuitPythonFor microcontrollers
GraalPyOn GraalVM, interop with Java
PyodideCPython compiled to WebAssembly, runs in browsers
Key takeaways
  • 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.