0Pricing
Python Academy · Lesson

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))   # 3

sys.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

All lessons in this course

  1. CPython Reference Counting
  2. The Garbage Collector and Cyclic References
  3. Profiling with cProfile and line_profiler
  4. Memory Profiling with tracemalloc
← Back to Python Academy