Sub topic 3
Reference counting: how most objects are freed
This chapter assumes you know that a Python variable is a name bound to an object. It also assumes you can tell mutable objects from immutable ones, and that you know why b = a makes two names for one list. Those ideas come from the first two chapters. Here you will learn the mechanism CPython uses to decide when an object can be freed.
The core idea
Every CPython object carries a reference count, an integer that records how many references currently point to it. When the count drops to zero, nobody can reach the object, so CPython frees it immediately. The program does not wait for a later cleanup pass.
This is why most Python programs release memory predictably. A temporary list built inside a function is gone when the function returns. A file object that goes out of scope is closed and freed at that point.
Reference counting is specific to CPython, the reference implementation. Other implementations such as PyPy use different strategies, so code should not depend on the exact moment an object is freed.
What changes a reference count
A reference is any place that holds a pointer to the object and keeps it alive. These events add or remove references:
| Event | Effect on the count |
|---|---|
| Binding a name (`a = obj`) | +1 |
| Rebinding or deleting the name (`a = other`, `del a`) | -1 for the old object |
| Storing it in a container (`lst.append(obj)`, `d[k] = obj`) | +1 |
| Removing it from a container (`lst.pop()`, `del d[k]`) | -1 |
| Passing it as an argument | +1 while the call runs |
| A function's local names when the function returns | -1 for each |
Only references that own the object count. Weak references, covered in a later chapter, do not.
Inspecting counts with sys.getrefcount
sys.getrefcount(obj) returns the current count. The result is always one higher than the number of names you can see, because passing obj as the argument creates a temporary reference.
import sys
a = []
print(sys.getrefcount(a)) # 2: the name a plus the temporary argument
b = a
print(sys.getrefcount(a)) # 3
del b
print(sys.getrefcount(a)) # 2Containers also hold references. Comparing the count before and after is more reliable than relying on absolute numbers, which can vary between Python versions.
import sys
x = object()
before = sys.getrefcount(x)
box = [x]
print(sys.getrefcount(x) - before) # 1: the list holds a reference
box.clear()
print(sys.getrefcount(x) - before) # 0: the list let goImmortal objects
Since Python 3.12, some objects are immortal. Examples are None, True, False, and small integers. Their count never changes and they are never freed. Calling sys.getrefcount(None) returns a very large fixed number on those versions. The count for such an object tells you nothing about how many names refer to it. Use ordinary objects, such as instances of your own classes, when experimenting.
Watching an object die
A __del__ method runs just before an object is freed. It makes the moment of deallocation visible. This class prints a message when that happens.
class Tracer:
def __init__(self, name):
self.name = name
def __del__(self):
print(f"freed {self.name}")
t = Tracer("one")
alias = t
del t
print("after del t") # nothing freed yet: alias still refers to it
del alias # prints "freed one" here
print("after del alias")The output is after del t, then freed one, then after del alias. Deleting t removed a name, not the object. The object was freed only when the last reference disappeared.
Local names follow the same rule. A function's locals are released when its frame is torn down:
class Tracer:
def __init__(self, name):
self.name = name
def __del__(self):
print(f"freed {self.name}")
def work():
t = Tracer("local")
print("working")
work() # prints "working", then "freed local"
print("after call")Rebinding also releases the old object. In t = Tracer("a") followed by t = Tracer("b"), Python builds the second object first, then binds the name, and only then releases the first object. For a moment both objects exist, which matters if you are close to a memory limit.
What happens when the count reaches zero
The following diagram shows the sequence CPython follows when a reference is dropped.
The loop from "release references the object holds" back to the zero check is what makes freeing cascade. When a list is freed, every item loses one reference. Any item that was referenced only by that list is freed in turn, and so on down a nested structure. CPython limits the recursion depth of this process, so freeing a very deeply nested structure does not overflow the C stack.
"Returned to the allocator" does not always mean "returned to the operating system". The allocator often keeps freed memory for reuse. A later chapter on pymalloc explains why a process's memory use may not shrink after you free objects.
Where references hide
An object stays alive when something you forgot still refers to it. These sources are easy to miss:
- Module globals and class attributes. These live as long as the module or class does.
- Caches and registries. A dictionary that maps keys to objects keeps every value alive until you remove the entry.
- Closures. A nested function holds references to the outer variables it uses.
- Exceptions and tracebacks. A traceback refers to the frames it passed through, and each frame refers to its local variables. Storing a caught exception can keep large locals alive.
- The interactive interpreter. It keeps the last result in
_.
Python protects you from one common case. In except Exception as e:, the name e is deleted when the except block ends. Without that, the exception, its traceback, and the frame would form a cycle through e.
Costs and limits
Reference counting has strengths and weaknesses.
Strengths:
- Objects are freed at a predictable point, so resources such as file handles do not linger in CPython.
- Memory is reclaimed as soon as possible, with no pause for a full scan.
Weaknesses:
- Overhead on every operation. Each assignment, argument pass, and container store updates a count.
- Cycles are not freed. If object A refers to B and B refers back to A, both counts stay above zero even when nothing else reaches them. Cleaning up cycles is the job of the cyclic garbage collector, the next major topic.
- Thread safety. In the standard build, the Global Interpreter Lock protects the counts from concurrent updates. The free-threaded build introduced in Python 3.13 uses a different, more elaborate scheme.
- Copy-on-write. Merely reading an object changes its count, which writes to its memory. After a
fork, this can force the operating system to copy pages that look read-only to your program.
A practical consequence is that you should not rely on __del__ for essential cleanup. In CPython it usually runs at a predictable time, but other implementations differ, and cycles delay or complicate it. Use with blocks and try/finally for resources that must be released.
Common errors
- Expecting
del xto free the object.delremoves one name. The object is freed only if that was the last reference. - Forgetting the temporary reference. Reading a count of 2 for an object with one name is correct.
- Testing with small integers or strings. Immortal or cached objects give misleading counts.
- Assuming locals vanish while an exception is held. A stored exception can keep its traceback frames, and their locals, alive.
Exercise
The code below creates a Tracer, appends it to a list, and then deletes the name t. When does "freed item" print, and what must you do to make it print?
t = Tracer("item")
registry = [t]
del t
print("deleted name")
Show answer
It does not print at del t. The list registry still holds a reference, so the count stays at 1 after the name is removed. "deleted name" prints first. "freed item" prints only when the last reference goes away, for example after registry.clear() or del registry, assuming nothing else refers to the object.
Exercise
Why does sys.getrefcount(a) report 2 for a list bound to a single name a?
Show answer
One reference is the name a. The second is the temporary reference created when a is passed as the argument to getrefcount. The function sees both while it runs.