Course Overview
Python Mastery & Linear Algebra for AICPython Memory Internals, Reference Counts & Garbage Collection
0% Done
Written Guide20 minutes
CPython Memory Internals, Reference Counts & Garbage Collection
Lesson Summary: 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.
