← Back to Python, page 1

python-0019 · Hard senior

How does Python manage memory: reference counting, the cyclic garbage collector, and what you can observe?

CPython frees most objects immediately through reference counting: each object counts the references to it and is deallocated when the count reaches zero. Reference cycles, such as two objects pointing at each other, never reach zero, so a generational cyclic garbage collector periodically finds and frees unreachable cycles. weakref lets you refer to an object without keeping it alive.

Full answer
python
import gc, sys, weakref

class Node:
    def __init__(self, name): self.name, self.other = name, None
    def __del__(self): print("freed", self.name)

n = Node("a")
print("refcount:", sys.getrefcount(n))
del n

gc.disable()
x, y = Node("x"), Node("y")
x.other, y.other = y, x
del x, y
print("cycle still alive before collect")
print("collected something:", gc.collect() > 0)
gc.enable()

z = Node("z")
r = weakref.ref(z)
print(r() is z)
del z
print(r())

Output:

text
refcount: 2
freed a
cycle still alive before collect
freed x
freed y
collected something: True
True
freed z
None

sys.getrefcount reports one more than expected because passing the object to the function adds a temporary reference. Deleting the last strong reference to Node('a') triggers __del__ immediately: that is reference counting at work. The two nodes that point at each other are not freed when their names are deleted; they are collected only when gc.collect() runs, which reports the number of unreachable objects found (the exact count includes their attribute dictionaries in some versions, so the run prints only whether anything was collected).

A weak reference returns the object while it lives and None afterwards, which is how caches avoid keeping objects alive (weakref.WeakValueDictionary).

Practical points: memory leaks in Python usually come from references that are kept unintentionally (global caches, closures, long-lived lists), not from the collector failing. tracemalloc helps find where memory is allocated. Other interpreters such as PyPy use different strategies, so do not rely on immediate __del__ timing.

python
import gc, sys, weakref

class Node:
    def __init__(self, name): self.name, self.other = name, None
    def __del__(self): print("freed", self.name)

n = Node("a")
print("refcount:", sys.getrefcount(n))
del n

gc.disable()
x, y = Node("x"), Node("y")
x.other, y.other = y, x
del x, y
print("cycle still alive before collect")
print("collected something:", gc.collect() > 0)
gc.enable()

z = Node("z")
r = weakref.ref(z)
print(r() is z)
del z
print(r())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Reference counting frees most objects immediately
  • Cycles need the cyclic collector
  • gc.collect forces a collection
  • weakref refers without keeping alive
  • Leaks usually come from kept references

Common mistakes

  • Relying on __del__ timing
  • Assuming the collector fixes all leaks

Follow-ups

  • What are the GC generations?
  • How would you find a memory leak with tracemalloc?

Tips

  • Separate refcounting from cycle collection