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.
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:
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")