Weak References with weakref (Breaking Circular References)
1Concept
A `weakref` references an object without increasing its `ob_refcnt`. When all strong references are deleted, the object is deallocated immediately, and the weak reference resolves to `None`. `WeakValueDictionary` is ideal for building memory-safe in-memory caches.
2Architecture Diagram
Strong Ref: RefCount + 1 (Keeps object alive) Weak Ref: RefCount Unchanged (Allows object to be collected when strong refs die)
3Code Example
Python 3.12
import weakref
class HeavyResource:
def __init__(self, name):
self.name = name
res = HeavyResource("ImageData")
wref = weakref.ref(res)
print(f"WeakRef before delete: {wref().name}")
del res # Delete only strong reference
print(f"WeakRef after delete: {wref()} (Automatically cleared!)")4Expected Output
WeakRef before delete: ImageData WeakRef after delete: None (Automatically cleared!)
5Key Takeaways
- ✓Weak references break circular dependency chains in tree/graph data structures.
- ✓`weakref.WeakValueDictionary` automatically evicts cache entries when objects lose strong references.
- ✓Some built-in types (like `list` and `dict`) do not support weak references directly.