WeakValueDictionary drops an entry when no strong reference keeps its value alive.
Make this comfortable
Python weak-value cache: an entry does not own its result
Operation contract
A receipt snapshot is inserted into a weak-value index while a caller holds it. Once that caller releases the last strong reference, collection removes the cache entry. The explicit collection makes the local CPython result observable; the timing is not a portable cache-expiration clock.
Failure and ownership boundary
A weak cache cannot promise a hit even moments after insertion. Some built-in values cannot be weakly referenced. Do not store the only copy of business data here, and do not rely on a weak-reference callback to close a critical resource or commit a transaction.
Working program
import gc
import weakref
class ReceiptSnapshot:
def __init__(self, revision):
self.revision = revision
snapshots = weakref.WeakValueDictionary()
current = ReceiptSnapshot(47)
snapshots["north-47"] = current
print("held", "north-47" in snapshots)
del current
gc.collect()
print("after_release", "north-47" in snapshots)Output
held True
after_release FalseCosts and limits
Lookup is expected O(1), but entries disappear with object lifetime. Recomputing a missing value can dominate dictionary cost.
Common Mistakes
- A weak cache is not a durable store.
- Garbage collection is not a request deadline.
- Resource cleanup must have an explicit owner.
Connected lessons
python
weakref-cache-ownership
