Python Weak References: Observing Objects Without Keeping Them Alive
An examination of the weakref module, from references with callbacks and proxies to weak containers, WeakMethod and finalize, with the objects that support weak references and the limits of weak caches.
Every ordinary reference in Python keeps its object alive: as long as a variable, a list or an attribute points to an object, the interpreter cannot release it. Most of the time this is exactly the desired behaviour, but registries, observers and metadata tables need the opposite, namely to remember an object without being the reason it stays in memory. The module weakref provides references of that second kind. The present article examines the module as a whole, from the basic reference and its callbacks to proxies, weak containers, weak references to methods and finalizers, and it identifies the cases in which weak references do not behave as expected. A reference that observes without owning is the secret weapon of this module.
Strong and Weak References
CPython destroys an object as soon as its reference count reaches zero, a mechanism described in the article devoted to memory management, which also shows how a weak back-reference breaks a cycle between a parent and its children. A weak reference does not contribute to that count. Calling it returns the object while the object exists and None afterwards, and an optional callback runs at the moment of destruction.
import weakref
class Sensor:
def __init__(self, name):
self.name = name
sensor = Sensor("thermometer")
reference = weakref.ref(sensor, lambda ref: print("sensor released"))
print(reference().name) # Output: thermometer
print(weakref.getweakrefcount(sensor)) # Output: 1
del sensor # Output: sensor released
print(reference()) # Output: None
The object disappears at the del statement, without waiting for any collector, because the weak reference was not counted. The callback receives the reference object itself, already dead, which makes it suitable for removing entries from a registry that points to the released object.
Which Objects Accept Weak References
Not every object can be the target of a weak reference, because the object must reserve a field in which the interpreter records its weak references. Instances of ordinary classes, functions, sets, generators and type objects have that field; several built-in types do not.
import weakref
class Tags(list):
pass
class Point:
__slots__ = ("x", "y")
class TrackedPoint:
__slots__ = ("x", "y", "__weakref__")
for candidate in ([], {}, 42, "text", (1, 2), {1, 2}, Tags(), Point(), TrackedPoint()):
try:
weakref.ref(candidate)
print(type(candidate).__name__, "accepted")
except TypeError:
print(type(candidate).__name__, "rejected")
# Output: list rejected, dict rejected, int rejected, str rejected, tuple rejected
# Output: set accepted, Tags accepted, Point rejected, TrackedPoint accepted
A list cannot be weakly referenced, but a subclass of list can, because the subclass adds the missing field; int and tuple, on the other hand, reject weak references even when subclassed. The two classes with __slots__ show the interaction with the optimization described in the article devoted to __slots__: declaring slots removes the field for weak references, and adding the name "__weakref__" to the slots restores it.
Proxies
A proxy, created with weakref.proxy, is a weak reference that does not need to be called: attribute access and operators are forwarded to the object directly. In the words of an old hermit from a galaxy far away, "These aren't the droids you're looking for", and indeed a proxy is a different object from the one it represents, although it answers for it, as the following example shows.
import weakref
class Account:
def __init__(self, owner):
self.owner = owner
account = Account("Ada")
proxy = weakref.proxy(account)
print(proxy.owner) # Output: Ada
print(proxy is account) # Output: False
print(type(proxy).__name__) # Output: ProxyType
print(isinstance(proxy, Account)) # Output: True
del account
try:
proxy.owner
except ReferenceError as error:
print(error) # Output: weakly-referenced object no longer exists
The proxy even passes the isinstance check, because it forwards the attribute __class__, but an identity comparison reveals the substitution. Its main disadvantage is the failure mode: where a dead ref returns None, which can be tested, a dead proxy raises ReferenceError at the first use, possibly far from the place where the object was released.
Weak Containers
Three containers apply weak references to whole collections. WeakKeyDictionary holds its keys weakly, which suits metadata attached to objects that the dictionary does not own; WeakValueDictionary holds its values weakly, which suits registries that map names to live objects; and WeakSet holds its members weakly, which suits lists of listeners.
import weakref
class Widget:
def __init__(self, name):
self.name = name
def notify(self, event):
print(f"{self.name} received {event}")
listeners = weakref.WeakSet()
metadata = weakref.WeakKeyDictionary()
button, slider = Widget("button"), Widget("slider")
for widget in (button, slider):
listeners.add(widget)
metadata[widget] = {"created_by": "layout"}
del slider
for widget in listeners:
widget.notify("resize") # Output: button received resize
print(len(listeners), len(metadata)) # Output: 1 1
The deleted slider disappears from both containers without any explicit removal, so the event source never notifies an object that the rest of the program has already abandoned. Since Python 3.9, both weak dictionaries also support the operators | and |= introduced for dictionaries by PEP 584.
Weak References to Methods and Finalizers
Two further tools, both added in Python 3.4, solve problems that a plain ref cannot handle. A bound method is created anew every time it is accessed, a consequence of the descriptor protocol examined in the article devoted to descriptors, so a weak reference to it dies immediately; WeakMethod stores the instance and the function separately and recreates the bound method on demand. A finalize object, in turn, registers a function to run when an object is released, and it is more reliable than __del__ because it never resurrects the object and can be called explicitly.
import weakref
class Logger:
def write(self, message):
return f"logged: {message}"
logger = Logger()
print(weakref.ref(logger.write)()) # Output: None
callback = weakref.WeakMethod(logger.write)
print(callback()("start")) # Output: logged: start
cleanup = weakref.finalize(logger, print, "logger closed")
print(cleanup.alive) # Output: True
del logger # Output: logger closed
print(callback(), cleanup.alive) # Output: None False
The first line confirms that an ordinary weak reference to logger.write is already dead when it is created. The finalizer must not receive a reference to the object itself among its arguments, since that reference would keep the object alive forever; here it receives only the function print and a message.
Pitfalls of Weak References
Weak references solve ownership problems, yet they are often expected to do more than they do. Five pitfalls are distinguished, which are the following:
WeakValueDictionaryis not a cache. An entry lives only while another part of the program holds the value, so a value stored only in the dictionary disappears at once; a real cache needs strong references and an eviction policy, such asfunctools.lru_cache.- Unsupported types. Lists, dictionaries, strings, integers and tuples cannot be weakly referenced directly.
- Dead proxies. A proxy raises
ReferenceErrorinstead of returningNone, so its failures appear far from their cause. - Bound methods.
weakref.ref(obj.method)is dead immediately;WeakMethodis required. - Strong references hidden in callbacks. A callback or finalizer that captures the object keeps it alive and is never triggered.
The first pitfall, which is the most common misunderstanding, is reproduced in the following example.
import weakref
class Report:
def __init__(self, key):
self.key = key
cache = weakref.WeakValueDictionary()
cache["sales"] = Report("sales")
print(len(cache)) # Output: 0
report = Report("costs")
cache["costs"] = report
print(len(cache)) # Output: 1
del report
print(len(cache)) # Output: 0
The first report vanishes as soon as the assignment ends, because the dictionary was its only holder. The structure is therefore an index of objects that live elsewhere, which is valuable for deduplicating live instances, but it does not keep anything for later use.
Choosing the Right Tool
Consequently, weak references belong wherever one part of a program must know about an object without owning it, and each tool of the module covers a particular shape of that need, as the following table summarizes.
| Need | Recommended tool |
|---|---|
| Refer to an object without keeping it alive | weakref.ref, optionally with a callback |
| Transparent access to an object that may disappear | weakref.proxy, with handling of ReferenceError |
| Attach data to objects the code does not own | weakref.WeakKeyDictionary |
| Registry of live objects by name or identifier | weakref.WeakValueDictionary |
| Listeners or observers that must not be kept alive | weakref.WeakSet, or WeakMethod for bound methods |
| Run cleanup code when an object is released | weakref.finalize |
| Keep results for later reuse | functools.lru_cache or a dictionary with eviction, not weak references |
Conclusion
It is concluded that a weak reference lets a program remember an object without extending its life, and that the module weakref builds on this single idea a family of tools: callbacks that announce destruction, proxies that stand in for the object, containers that clean themselves, WeakMethod for bound methods and finalize for reliable cleanup. This magic has precise limits, since only objects with a field for weak references can be targets, and a weak container keeps nothing that the rest of the program has released. The Observer pattern, in which a subject notifies a changing set of listeners that it must not keep alive, is the natural application of these tools and is developed in a future article of this series.