CPython Reference Counting
Understand how CPython tracks object lifetimes with refcounts.
What Is Reference Counting?
CPython tracks every object's reference count. When the count drops to 0, the object is immediately deallocated. This is Python's primary memory management mechanism.
import sys
x = [1, 2, 3]
print(sys.getrefcount(x)) # 2 (x + getrefcount arg)
y = x
print(sys.getrefcount(x)) # 3sys.getrefcount()
sys.getrefcount(obj) returns the current reference count. Note: calling it adds 1 (the function argument reference).
import sys
a = "hello"
print(sys.getrefcount(a)) # baseline (may be high for interned strings)
b = a
print(sys.getrefcount(a)) # one more
del b
print(sys.getrefcount(a)) # back to baseline