1.Reference counting
Every CPython object carries a count of how many references point at it. A new name, container slot, or argument binding increments it; del, rebinding, or scope exit decrements it. The object is freed the instant the count hits zero.
Key features
- sys.getrefcount(obj) over-reports by one — passing obj to it adds a temporary reference
- A name binding, a container slot, and a function argument each count as one reference
- del name, rebinding a name, and a function returning all decrement a held reference
- The count reaching zero triggers immediate deallocation — most objects die instantly
- Reference counting alone cannot free a cycle — mutual references never reach zero
What changes the reference count
- obj = object() — refcount 1
- alias = obj — refcount 2 — a second reference
- del obj; del alias — refcount 0 — freed instantly
Command
import sys
sys.getrefcount(obj) # int — includes +1 for getrefcount's own argument
del name # decrements one reference
x = new_value # decrements the old object's count, increments the new one'sEvery object carries a refcount; freed the instant it hits zero. sys.getrefcount(obj) reports one extra, for its own reference. Alone, it cannot free a cycle.