Reference counting
Reference counting is CPython's first memory manager: each object stores how many names and containers point at it. When the count hits zero, the object is deallocated immediately.
Detailed Explanation
Every CPython object starts with a count. Binding a name increments it. Rebinding or deleting the name decrements it. A list holding the object increments. A function's frame holding it in f_locals increments. sys.getrefcount(obj) returns the count plus one extra because passing obj into the function is itself a reference.
When the count reaches zero, CPython runs the deallocator: __del__ if present, then free. File objects often close here if you forgot with. That promptness is why people say "Python cleans up at the end of the block" even without a context manager. It is not a language guarantee. PyPy, the free-threaded build, and future runtimes may delay or omit immediate destruction. Use with for resources.
Cycles break naive counting. A and B pointing at each other never reach zero. CPython's cyclic garbage collector finds those. Objects with a __del__ in a cycle are harder; prefer not to write __del__.
The GIL exists in large part because incrementing the count from two threads without a lock is a data race. Reference counting is cheap per assignment and still not free: a tight loop that rebinds names pays for inc/dec traffic.
You cannot (and should not) set the count yourself. del name decrements the name's target; it does not destroy the object if another reference exists. weakref holds without incrementing, so caches can forget objects that nobody else needs.
Other implementations may not use refcounting. Write for the language: drop references when you are done, use context managers, do not rely on __del__ for correctness.
Code Examples
import sys
payload = ["order"]
print(sys.getrefcount(payload)) # 2: name + the argument to getrefcount
alias = payload
print(sys.getrefcount(payload)) # 3
del alias
print(sys.getrefcount(payload)) # 2# The object lives as long as the container does.
box = []
obj = {"sku": "A-1"}
box.append(obj)
del obj
print(box[0]) # still {'sku': 'A-1'}Common Gotchas
Treating `del` as a destructor
`del x` unbinds the name. Other aliases keep the object.
Prompt `close()` is a CPython courtesy
put cleanup in `with`, not in "the last line dropped the ref".
`getrefcount` is not stable across builds
the extra references from the function call and from interned objects confuse demos. Use it for teaching, not for production logic.
Cycles need the other collector
refcount alone will not free a doubly-linked list of nodes that still point at each other.