Sub topic 3
Reference counting: how most objects are freed
This chapter assumes you know Python functions, classes, lists, and dictionaries. It also assumes you know that names are bound to objects, and that you are running CPython, the standard interpreter.
The idea
Every CPython object carries a counter. The counter records how many references point to the object. A reference is anything that keeps the object reachable: a variable name, a list slot, a dictionary value, an attribute, or a function argument.
When the counter drops to zero, CPython frees the object immediately. No background process has to find it first. This is why most objects in a Python program disappear at a predictable moment.
What changes the count
The count goes up when you:
- bind a name to the object (
b = a) - put the object in a container such as a list or dictionary
- pass it as an argument to a function
The count goes down when you:
- use
delon a name - rebind a name to something else
- leave a function whose local names held the object
- remove the object from a container, or free the container itself
Watching the count
The function sys.getrefcount returns an object's current count.
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)) # 2The result is always one higher than you might expect. Passing a to getrefcount creates a temporary reference for the duration of the call. Treat the number as "names holding the object, plus one".
Note that del b removes the name b. It does not delete the list. The list is freed only when the last reference goes away.
Freeing cascades
Freeing an object also drops the references it held. If that brings other objects to zero, they are freed too.
import weakref
class Item:
pass
class Box:
def __init__(self):
self.item = Item()
box = Box()
probe = weakref.ref(box.item)
print(probe() is not None) # True
del box
print(probe()) # None: the Box was freed, then its ItemHere probe is a weak reference. It lets us observe the object without adding to its count. Weak references get their own chapter. For now, treat probe() as a way to ask "is the object still alive?"
Function scope
Local names disappear when a function returns, so the objects they referred to lose a reference.
import sys
def work(shared):
local = shared # count goes up by one inside the call
return sys.getrefcount(shared)
data = [1, 2, 3]
print(sys.getrefcount(data)) # 2
print(work(data)) # higher than 2 while the function runs
print(sys.getrefcount(data)) # 2 again after it returnsAdvantages and limits
Reference counting gives prompt cleanup. A file object or a large list can be released as soon as you stop using it. It also keeps memory use steady, because there are no long pauses while a collector scans everything.
It has costs. Every assignment must update a counter. And it cannot free objects that refer to each other, because each one keeps the other's count above zero even when nothing else can reach them. The next chapters on object lifetime and the cyclic garbage collector cover how CPython handles this.
Common errors
- Reading
getrefcountliterally. The extra temporary reference makes the number one too high. Some small objects, such as small integers and interned strings, also show large counts because the interpreter shares them. - Expecting
delto free memory.delonly removes one name. The object survives if anything else refers to it. - Assuming this applies everywhere. Immediate freeing is a CPython behavior. Other implementations, such as PyPy, use different strategies and may free objects later.
- Forgetting hidden references. A traceback, a global list, a cache, or a closure can hold an object and keep its count above zero.
Exercise
You run a = [], then b = a, then c = [a], then del a. How many references to the list remain, and which ones are they?
Show answer
Two remain: the name b and the slot inside the list c. The del a removed only the name a, so the list stays alive. sys.getrefcount(b) would print 3 because of the temporary argument reference.
Exercise
Why does sys.getrefcount(x) return 2 for an object that has exactly one name, x?
Show answer
One reference is the name x. The second is the temporary reference created when x is passed as the argument to getrefcount.