Phase 9 of 25 · Topic 9.1

CPython Reference Counting Mechanism & ob_refcnt

1Concept

CPython's primary memory management system is Reference Counting. Every object maintains an internal `ob_refcnt` counter. When a reference is created (assignment, function argument, container storage), refcount increments; when a reference goes out of scope or is deleted (`del`), it decrements. When refcount hits 0, memory is deallocated immediately.

2Architecture Diagram

a = [1, 2] (refcount=1) ---> b = a (refcount=2) ---> del a (refcount=1) ---> del b (refcount=0: Deallocated!)

3Code Example

Python 3.12
import sys

data = ["CacheItem"]
print(f"Ref count: {sys.getrefcount(data) - 1} (sys.getrefcount adds 1 temp ref)")

alias = data
print(f"Ref count after alias: {sys.getrefcount(data) - 1}")

del alias
print(f"Ref count after del:   {sys.getrefcount(data) - 1}")

4Expected Output

Ref count: 1 (sys.getrefcount adds 1 temp ref)
Ref count after alias: 2
Ref count after del:   1

5Key Takeaways

  • `sys.getrefcount(obj)` returns 1 higher than expected because passing `obj` creates a temporary reference.
  • Reference counting provides deterministic, immediate deallocation for non-cyclic objects.
  • Reference counting cannot collect circular references (e.g. `a.next = a`).