Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python weak-value cache: an entry does not own its result

Last updated: 1 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

WeakValueDictionary drops an entry when no strong reference keeps its value alive.

Download Python source kit

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

python
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

Output
held True
after_release False

Costs 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

Test this boundary.

python
weakref-cache-ownership
Storage details