The Canon / lab 2

The count, the cycle and what
holds on to memory

Three scenarios, step by step: where the count is enough, where it is powerless in principle, and what a real leak looks like.

for chapters 09 and 10the steps are deterministicthe count arithmetic is exact

Reference counting is described in one sentence — “an object lives as long as someone is looking at it” — and from that sentence follow a working with, the impossibility of collecting a cycle, and half the leaks in production. Below, that sentence is unwound step by step. The number in the circle is the value of ob_refcnt, the very field from the first lab.

1Check it by hand

The second scenario reproduces in full and shows the same thing in numbers. Paste it as it is:

import gc, sys

class Node:
    def __init__(self, name): self.name, self.next = name, None
    def __repr__(self): return f"Node({self.name!r})"

a, b = Node("A"), Node("B")
a.next, b.next = b, a
print("rc(A):", sys.getrefcount(a) - 1)   # -1: the getrefcount argument is a reference too
# → rc(A): 2

gc.collect()                 # clean up so the count is honest
tracked_before = len(gc.get_objects())
del a, b                     # no names left, the objects are unreachable
print("collected by refcount:", len(gc.get_objects()) - tracked_before)
# → collected by refcount: 0      ← not a single one died

print("collected by traversal:", gc.collect())
# → collected by traversal: 2

2What follows from this

The count arithmetic in the scenarios is exact: every number here is what sys.getrefcount returns, minus one for its own argument. The order of destruction in the third scenario is real too: CPython takes the chain apart from the outer object to the inner one, because each destruction drops the next reference.

Written by · The Python Canon