A regular reference keeps an object alive. weakref lets code observe it without preventing collection after strong references disappear. This is useful for caches, registries, and auxiliary associations.
from weakref import WeakValueDictionary
class Image:
def __init__(self, path: str) -> None:
self.path = path
cache: WeakValueDictionary[str, Image] = WeakValueDictionary()
image = Image("cover.png")
cache[image.path] = image
assert cache["cover.png"] is image
How to use it safely
Not every type supports weak references. An entry may disappear between operations, so retrieve it once and test the result. Do not treat weakref as a replacement for an explicit cache policy with size and expiration limits.
To strengthen the foundation, read Python collections guide and type hints guide.
The official Python documentation, accessed July 22, 2026, describes the API, edge cases, and version compatibility.