PythiloLesson 2 of 12 · progress kept in this browser

Cache without owning object lifetimes

A cache normally holds strong references, extending the lifetime of every value it stores. That can accidentally turn a memory optimization into unbounded retention. A WeakValueDictionary permits reuse while a caller still owns the object, but does not keep an otherwise unused object alive.

Weak references are not a replacement for resource cleanup or a bounded LRU cache. Not every Python value supports them, and an entry can disappear between accesses. Keep a strong local reference while returning a value. This exercise uses user-defined objects and explicit collection instead of relying on CPython reference-count timing.

import weakref, gc
class Item: pass
value = Item()
cache = weakref.WeakValueDictionary()
cache["x"] = value
del value
gc.collect()
print(list(cache))
Your task

Implement weak_cache(factory) returning get(key). Reuse a live value for that key without retaining it after all callers drop it. Values support weak references.