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))Review the design
A weak cache delegates lifetime to callers. Losing an entry is normal behavior, so factory calls must be safe to repeat. Resource release still belongs in explicit context management, not in a finalizer.
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.
The explanation opens here once every check passes.