Weak References with weakref.ref
`weakref.ref(obj)` references an object without incrementing its reference count. When the last strong reference is deleted, the object is immediately garbage collected 🔗.
import weakref
class HeavyBuffer:
def __init__(self, data):
self.data = data
buf = HeavyBuffer("100MB payload")
ref = weakref.ref(buf)
print(ref() is buf) # True (dereferences object) 🔗
del buf # Destroy last strong reference!
print(ref()) # None! Automatically cleared 🗑️
# 85. Weak References with weakref.ref `weakref.ref(obj)` references an object without incrementing its reference count. When the last strong reference is deleted, the object is immediately garbage collected 🔗. ```python import weakref class HeavyBuffer: def __init__(self, data): self.data = data buf = HeavyBuffer("100MB payload") ref = weakref.ref(buf) print(ref() is buf) # True (dereferences object) 🔗 del buf # Destroy last strong reference! print(ref()) # None! Automatically cleared 🗑️ ``` Weak references are indispensable for caches and observer patterns where caching an object shouldn't keep it alive in memory when unused! 🔗 --- ### Question What does a weak reference `ref()` return after the original target object has been deleted? 🧠 - [ ] a. `None` 🗑️ - [ ] b. A dangling C pointer exception - [ ] c. A reconstructed copy of the original object - [ ] d. An empty dictionary `{}` --- ### Challenge Import `weakref`. Create class `Node: pass`. Create `n = Node()`, create `w = weakref.ref(n)`. Print `w() is n`. 🎯 <details> <summary>Solution</summary> ```python import weakref class Node: pass n = Node() w = weakref.ref(n) print(w() is n) ``` </details>