article Lesson 20 min

CPython Memory Internals, Reference Counts & Garbage Collection

Understanding PyObject headers, arena allocators, cyclic reference detection, and weakref mechanics.

Systems LabCPython Memory Model

CPython Stack & Heap Pointer Explorer

Explore how CPython manages memory pointers, cached singletons, and reference counting.

Select an Integer value to evaluate:

CPython pre-allocates an internal cache for integers between [-5, 256].

Stack (Namespace Pointers)
var a0xCAFE00
var b0xCAFE00
Heap (PyObject Allocations)
PyLongObject (Shared Cached Singleton)0xCAFE00
ob_refcnt: 184 (shared by runtime)
ob_ival: 256
a = 256; b = 256
a == b: True (Values are equal)a is b: True (Same memory address)

Every variable in Python is a pointer referencing an underlying PyObject allocated on the heap. In this lesson, we explore how CPython tracks reference counts and when the cyclic garbage collector triggers generation-based sweeps.

import sys
import gc

a = [1, 2, 3]
print("Initial Refcount:", sys.getrefcount(a) - 1)  # getrefcount adds 1 temporary ref

b = a
print("After assignment:", sys.getrefcount(a) - 1)  # 2

del b
print("After del:", sys.getrefcount(a) - 1)         # 1

Cyclic Garbage Collection

Reference counting cannot reclaim objects referencing each other in a closed loop. CPython’s generational GC tracks container objects across three generations (Gen 0, 1, and 2), identifying unreachable reference islands.

Python Systems: Interactive Lab

Python SystemsMatched to lesson

Inspects heap addresses, sys.getrefcount(), and integer caching.

Labs:
CPython Reference Counting & Object Interning
Python 3.13 • NumPy • PyTorch
Terminal Output

Click Run Code to execute this algorithm in the browser sandbox.

Finished this lesson?

Mark it as complete to record your progress and unlock the next module.