CPython Internals, Memory Model (PyObject & pymalloc), Garbage Collection & The GIL
- ✓ Every Python object starts with a 16-byte PyObject header on 64-bit machines (8-byte ob_refcnt + 8-byte ob_type pointer); variable-size objects (PyVarObject: int, str, list, tuple) add an 8-byte ob_size (24-byte header).
- ✓ CPython never calls OS malloc() for small objects (<= 512 bytes): pymalloc carves 1 MiB Arenas into 16 KiB Pools partitioned into fixed 8-byte size-class Blocks with O(1) free-list allocation.
- ✓ Memory is reclaimed via two mechanisms: immediate deterministic deallocation when ob_refcnt hits 0, plus a 3-generation Cyclic Garbage Collector (gc) that traverses container doubly-linked lists (PyGC_Head, +16 bytes) to break reference cycles.
- ✓ Declaring __slots__ on high-cardinality classes eliminates per-instance __dict__ and __weakref__ pointers, cutting RAM usage by 55–70%.
01.
C-Level Anatomy of PyObject, PyVarObject & PyGC_Head
In CPython (Include/object.h), every value—whether an integer, function, stack frame, or class—is allocated on the heap and referenced via a PyObject* pointer. Understanding the exact byte offsets explains why Python objects carry memory overhead and how to engineer around it:
/* 1. Optional 16-Byte Cyclic GC Header (prepended ONLY to container types: list, dict, tuple, instances) */
typedef struct {
uintptr_t _gc_next; // 8 bytes: Doubly-linked list next pointer in Generation 0/1/2
uintptr_t _gc_prev; // 8 bytes: Doubly-linked list prev pointer + refcount flags
} PyGC_Head; // ──▶ 16 bytes (placed immediately BEFORE PyObject in memory)
/* 2. Base 16-Byte PyObject Header (Every object in Python) */
struct _object {
Py_ssize_t ob_refcnt; // 8 bytes: Reference count (or PEP 683 Immortal bitmask 0xFFFFFFFF)
PyTypeObject *ob_type; // 8 bytes: Pointer to type descriptor (&PyLong_Type, &PyList_Type...)
}; // ──▶ 16 bytes (e.g. float = 16B header + 8B IEEE-754 double = 24 bytes)
/* 3. Variable-Length 24-Byte PyVarObject Header (int, str, bytes, tuple, list) */
typedef struct {
PyObject ob_base; // 16 bytes: ob_refcnt + ob_type
Py_ssize_t ob_size; // 8 bytes: Number of items/digits
} PyVarObject; // ──▶ 24 bytes (e.g. int(1) = 24B header + 4B uint32 digit = 28 bytes)
02.
The pymalloc 3-Tier Memory Allocator (Arenas → Pools → Blocks)
Because Python creates and destroys millions of small objects per second, calling the OS C library malloc() directly would thrash kernel locks and fragment virtual memory. Instead, CPython routes all allocations ≤ 512 bytes through pymalloc (Objects/obmalloc.c), while allocations > 512 bytes fall back to the system allocator:
┌─────────────────────────────────────────────────────────────────────────────────┐ │ TIER 1: ARENA (1 MiB on 64-bit / 256 KiB on 32-bit, allocated via OS mmap) │ │ Contains 64 contiguous Pools (each 16 KiB). Returned to OS only when ALL 64 │ │ Pools are completely empty. │ │ ┌───────────────────────────────────────┐ ┌──────────────────────────────────┐ │ │ │ TIER 2: POOL (16 KiB, page-aligned) │ │ POOL #2 (Size Class: 32 Bytes) │ │ │ │ Dedicated to ONE size class (e.g. │ │ States: used (has free blocks),│ │ │ │ 24B or 32B in 8-byte increments). │ │ full (all blocks allocated), │ │ │ │ ┌──────────┬──────────┬──────────┐ │ │ or empty (ready for any class) │ │ │ │ │ BLOCK 1 │ BLOCK 2 │ BLOCK 3 │ │ └──────────────────────────────────┘ │ │ │ │ (32 B) │ (32 B) │ FreeList │ │ │ │ │ └──────────┴──────────┴──────────┘ │ │ │ └───────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────────┘
03.
Interactive CPython Memory Footprint Simulator (class vs __slots__ vs array)
Slide to simulate storing N records in a 64-bit CPython 3.12+ worker process:
__dict__ + 84B field objs + 8B list ptr__dict__!) + 84B field objs + 8B ptrPyObject headers)04. Generational Cyclic GC, Immortal Objects (PEP 683) & Free-Threading (PEP 703)
| Subsystem | How It Works Internally | Production Tuning & Engineering Lever |
|---|---|---|
Reference Counting (ob_refcnt) |
Py_INCREF / Py_DECREF on every pointer bind/unbind. When ob_refcnt == 0, tp_dealloc frees memory immediately & deterministically. |
Inspect via sys.getrefcount(obj) - 1. Break parent↔child ownership cycles using weakref.ref(parent). |
3-Gen Cyclic GC (gc module) |
Tracks containers in Gen 0, Gen 1, Gen 2 doubly-linked lists. Subtracts internal references (tp_traverse) to find isolated reference islands unreachable from roots. |
Check thresholds via gc.get_threshold() (default (700, 10, 10)). Call gc.freeze() before os.fork() in Gunicorn/Uvicorn workers to prevent Copy-on-Write page dirtying! |
| PEP 683 Immortal Objects (3.12+) | Special sentinel refcount (_Py_IMMORTAL_REFCNT) on None, True, False, small ints [-5, 256], and interned strings makes Py_INCREF a no-op. |
Prevents CPU cache-line invalidation and OS Copy-on-Write memory bloat across multi-worker preforked servers. |
PEP 703 Free-Threading (python3.13t) |
Replaces the global GIL mutex with Biased Reference Counting (ob_tid owning thread fast-path + atomic shared counter) and per-object PyMutex locks. |
Check runtime status with sys._is_gil_enabled(). Allows pure-Python threading.Thread pools to scale linearly across all CPU cores. |
💻 Hands-On WebAssembly Python Labs (Module 5)
Click Run & Edit Live (Wasm) on any lab below to execute and modify the code in our browser Pyodide runtime.
Lab 5.1: Measuring PyObject Sizes, __slots__ Savings & Cyclic Garbage Collection Live
Run this live experiment to measure exact byte sizes of Python primitives, verify __slots__ memory reduction, and watch the Cyclic GC reclaim a self-referential object cycle.
from dataclasses import dataclass
import gc
import sys
import weakref
print("[1] Exact 64-Bit CPython PyObject Byte Sizes (sys.getsizeof):")
for obj in [None, True, 0, 2**30, 3.14, "", "a", (), [], {}, set()]:
print(f" {type(obj).__name__:<8} val={repr(obj):<12} -> {sys.getsizeof(obj):>3} bytes")
# 2. Standard Class (__dict__) vs. Slotted Class (__slots__)
class StandardNode:
def __init__(self, node_id: int, weight: float, label: str):
self.node_id = node_id
self.weight = weight
self.label = label
class SlottedNode:
__slots__ = ("node_id", "weight", "label")
def __init__(self, node_id: int, weight: float, label: str):
self.node_id = node_id
self.weight = weight
self.label = label
std = StandardNode(1, 0.95, "head")
slt = SlottedNode(1, 0.95, "head")
std_bytes = sys.getsizeof(std) + sys.getsizeof(std.__dict__)
slt_bytes = sys.getsizeof(slt)
print("\n[2] Per-Instance Memory Footprint (__dict__ vs __slots__):")
print(f" StandardNode (instance + __dict__): {std_bytes} bytes")
print(f" SlottedNode (fixed C descriptor): {slt_bytes} bytes ({100 * (1 - slt_bytes / std_bytes):.1f}% reduction!)")
# 3. Reference Cycle & Generational GC Collection
class GraphVertex:
def __init__(self, name: str):
self.name = name
self.neighbor = None
v1, v2 = GraphVertex("A"), GraphVertex("B")
v1.neighbor = v2
v2.neighbor = v1 # Reference cycle: refcount will stay 1 even after 'del v1, v2'!
weak_v1 = weakref.ref(v1)
gc.disable()
del v1, v2
print("\n[3] Cyclic Garbage Collector Verification:")
print(" After 'del v1, v2' (with GC disabled), is cycle still alive in RAM?", weak_v1() is not None)
reclaimed = gc.collect()
gc.enable()
print(f" After gc.collect() -> Reclaimed {reclaimed} unreachable cyclic objects! Alive now?", weak_v1() is not None)
Lab 5.2: Small Integer Caching, String Interning (sys.intern) & Zero-Copy memoryview
Verify CPython’s [-5, 256] singleton integer pool, string interning pointer deduplication, and zero-copy buffer slicing.
import sys
# 1. Small Integer Singleton Cache [-5, 256]
a = int("256")
b = int("256")
c = int("10000")
d = int("10000")
print("[1] Small Integer Singleton Pool [-5, 256]:")
print(f" int('256') is int('256') -> {a is b} (Same PyObject* address: {hex(id(a))})")
print(f" int('10000') is int('10000') -> {c is d} (Distinct heap allocations, use == for value!)")
# 2. String Interning (sys.intern) for High-Cardinality Dictionary Keys / Labels
s1 = sys.intern("tenant_organization_prod_us_east_1")
s2 = sys.intern("".join(["tenant", "_organization", "_prod_us_east_1"]))
print("\n[2] Explicit String Interning (sys.intern):")
print(f" s1 is s2 (O(1) pointer identity comparison!): {s1 is s2}")
# 3. Copying bytes slice vs. Zero-Copy memoryview slice
raw_buffer = bytearray(b"HEADER:001|PAYLOAD:AUTONOMOUS_AGENT_STREAM_DATA")
slice_copy = raw_buffer[19:] # Allocates new bytearray & copies bytes
slice_view = memoryview(raw_buffer)[19:] # Zero-copy window into raw_buffer!
# Mutate through the zero-copy memoryview
slice_view[0:10] = b"ZERO_COPY_"
print("\n[3] Zero-Copy memoryview Mutation:")
print(" Original raw_buffer after view edit:", raw_buffer.decode("utf-8"))
print(" Copied slice remained unchanged: ", slice_copy.decode("utf-8"))
Frequently Asked Staff Interview Questions (Module 5)
Why does a single Python integer (x = 1) consume 28 bytes of RAM instead of 4 or 8 bytes? ▸
In CPython, int is an arbitrary-precision PyLongObject (a PyVarObject). On 64-bit systems, it consists of: ob_refcnt (8 bytes) + ob_type pointer (8 bytes) + ob_size/lv_tag (8 bytes) + ob_digit[0] (4-byte uint32 limb) = 28 bytes total.
Why doesn’t a Python process immediately return memory to the OS after del big_list? ▸
When objects <= 512 bytes are freed, their memory blocks are returned to CPython’s internal pymalloc Pool free-lists for instant reuse by future Python allocations, not back to the OS kernel. An Arena (1 MiB) is only munmap()-ed back to the OS when every single one of its 64 Pools becomes 100% empty.
How does __slots__ save 60%+ memory on millions of class instances? ▸
A normal Python class instance allocates a dynamic hash table (instance.__dict__) to store attributes, costing ~112+ extra bytes per object. Adding __slots__ = ("x", "y") tells CPython to forbid __dict__ creation and instead pack attribute pointers into a fixed C array directly after the 16-byte PyObject header, accessed via C member_descriptor offsets.