← Back to Python, page 5

python-0091 · Hard senior

Use weak references to build a cache that does not keep objects alive.

A weak reference points to an object without increasing its reference count, so the object can be freed when nothing else uses it. weakref.WeakValueDictionary removes entries automatically when values die, which suits caches of large objects owned elsewhere. Not every type supports weak references; int, str and tuple do not.

Full answer
python
import gc, weakref

class Image:
    def __init__(self, name): self.name = name
    def __repr__(self): return f"Image({self.name})"

cache = weakref.WeakValueDictionary()
logo = Image("logo")
banner = Image("banner")
cache["logo"], cache["banner"] = logo, banner
print(sorted(cache.keys()))
del banner
gc.collect()
print(sorted(cache.keys()), cache.get("banner"))

r = weakref.ref(logo, lambda ref: print("logo finalised"))
print(r() is logo)
del logo
gc.collect()
print(r())
try:
    weakref.ref(42)
except TypeError as e:
    print("TypeError:", e)

Output:

text
['banner', 'logo']
['logo'] None
True
logo finalised
None
TypeError: cannot create weak reference to 'int' object

Deleting the last strong reference to the banner frees it, and its cache entry disappears without any cleanup code. The weakref.ref callback runs when the logo is freed, and calling the dead reference returns None. CPython frees objects as soon as their reference count drops to zero; gc.collect() is called only to make the example reliable if a cycle were involved. Weak references are also used for observer lists, so listeners do not keep subscribers alive, and weakref.finalize is the preferred cleanup hook.

python
import gc, weakref

class Image:
    def __init__(self, name): self.name = name
    def __repr__(self): return f"Image({self.name})"

cache = weakref.WeakValueDictionary()
logo = Image("logo")
banner = Image("banner")
cache["logo"], cache["banner"] = logo, banner
print(sorted(cache.keys()))
del banner
gc.collect()
print(sorted(cache.keys()), cache.get("banner"))

r = weakref.ref(logo, lambda ref: print("logo finalised"))
print(r() is logo)
del logo
gc.collect()
print(r())
try:
    weakref.ref(42)
except TypeError as e:
    print("TypeError:", e)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Weak references do not keep objects alive
  • WeakValueDictionary drops dead values
  • Callbacks run on finalisation
  • Built-in immutables do not support weakrefs
  • Useful for caches and observers

Common mistakes

  • Caches with strong references that leak memory
  • Relying on __del__ for cleanup

Follow-ups

  • How does weakref.finalize differ from __del__?
  • Why can't ints be weakly referenced?

Tips

  • Show automatic removal