Mastery
Mastery/Python/A. Object model, identity & memory
T2 · intermediate depth

Weak references

A weakref.ref points at an object without incrementing its reference count -- so holding a weak reference never keeps something alive. Calling it returns the object if it's still alive, or None once the last strong reference is gone. This is exactly the tool for caches and observer/listener registries that shouldn't be the reason an object outlives its usefulness.

python
import weakref

class Resource:
    pass

obj = Resource()
weak = weakref.ref(obj)

print("weak() while a strong reference still exists:", weak())
del obj
print("weak() after the only strong reference is gone:", weak())

weakref.finalize and WeakValueDictionary build on the same idea -- a cache that holds weak references lets its entries disappear naturally once nothing else needs them, without manual cleanup:

python
cache = weakref.WeakValueDictionary()

class Big:
    def __init__(self, name):
        self.name = name

item = Big("expensive-to-build")
cache["key"] = item
print("in cache while a strong ref exists:", "key" in cache)

del item
print("in cache after the strong ref is gone:", "key" in cache, "-- entry vanished on its own")

Interview angle

"How would you build a cache that doesn't cause a memory leak?" is a great open-ended question where weakref/WeakValueDictionary is the ideal answer for a specific class of cache (one that shouldn't be the reason an object stays alive). Candidates who reach for a plain dict cache without considering eviction or weak references are showing a real gap most people only close after debugging an actual memory leak.

In the industry

Weak references show up in observer/listener registries (so registering a callback doesn't keep the subscriber alive forever), object caches, and circular-reference-breaking patterns (e.g. a child object holding a weak reference back to its parent instead of a strong one). It's a deliberately narrow tool — most code never needs it — reached for specifically when "this collection shouldn't extend an object's lifetime" is a real requirement, not a default choice.