Full answer
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:
refcount: 2
freed a
cycle still alive before collect
freed x
freed y
collected something: True
True
freed z
Nonesys.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.
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