Sub topic 6
Weak references
This chapter assumes you know how reference counting works in CPython, including that an object is freed when its count reaches zero. It also assumes you can write Python classes and use dictionaries. A weak reference lets you point at an object without keeping it alive.
What a weak reference is
A normal reference, also called a strong reference, increases an object's reference count. As long as one strong reference exists, the object stays in memory.
A weak reference does not increase the count. If the only references left to an object are weak, the object is freed. The weak reference then reports that its target is gone.
import weakref
class Resource:
pass
obj = Resource()
ref = weakref.ref(obj)
print(ref() is obj) # True
del obj
print(ref()) # None in CPython, because the last strong reference is goneCalling the weak reference object, ref(), returns the target if it is still alive and None if it is not. The "None in CPython" comment matters. CPython frees the object the moment its count hits zero. Other implementations, such as PyPy, may free it later, so portable code must always handle the None case.
Using a weak reference safely
Because the target can disappear at any time, never test the reference and then call it again. Call it once and keep the result in a local name. That local name is a strong reference, so the object cannot vanish while you use it.
import weakref
class Resource:
def use(self):
return "working"
obj = Resource()
ref = weakref.ref(obj)
target = ref() # one call, stored in a strong name
if target is not None:
print(target.use()) # safe: target keeps the object aliveThis is wrong, because the object could be freed between the two calls:
# Fragile pattern, shown for contrast:
# if ref() is not None:
# ref().use() # the second call may return NoneIn CPython, ordinary single-threaded code rarely hits this race. Threads or a cycle collection can still trigger it, so the single-call pattern costs nothing and is the habit to keep.
Which objects can be weakly referenced
Not every object supports weak references. Instances of plain user-defined classes do. Several built-in types do not, because they have no slot to store the list of weak references.
- Instances of ordinary classes, functions, and methods support them. Bound methods are a special case, covered below.
- Plain
int,str,tuple,list, anddictobjects do not. - Subclasses of
list,dict, andsetdo, because the subclass adds the needed slot. - A class that defines
__slots__without"__weakref__"in it does not.
import weakref
class Plain:
pass
class Slotted:
__slots__ = ("x",)
class SlottedWeak:
__slots__ = ("x", "__weakref__")
class MyList(list):
pass
for factory in (Plain, Slotted, SlottedWeak, MyList, list):
try:
weakref.ref(factory())
print(factory.__name__, "supports weak references")
except TypeError as exc:
print(factory.__name__, "does not:", exc)This links to the __slots__ chapter. Removing __dict__ also removes __weakref__ unless you list it, so a memory-saving class can lose weak-reference support without warning.
Callbacks
weakref.ref accepts an optional callback. CPython calls it with the weak reference object itself after the target is about to be finalized. The weak reference already returns None at that point.
import weakref
class Resource:
pass
def on_dead(ref):
print("target was freed:", ref() is None)
obj = Resource()
ref = weakref.ref(obj, on_dead)
del obj # prints: target was freed: TrueThe callback receives the weak reference, not the object, because the object is gone. Exceptions raised in a callback are printed to standard error and ignored, so they cannot stop the program. The callback only runs while the weak reference object itself is alive. If you drop ref, the callback never fires.
Weak collections
Storing weak references by hand in your own dictionaries gets tedious. The weakref module provides three containers that do it for you.
| Container | Holds weakly | Entry removed when |
|---|---|---|
| `WeakValueDictionary` | the values | a value is freed |
| `WeakKeyDictionary` | the keys | a key is freed |
| `WeakSet` | the elements | an element is freed |
A cache that does not keep its entries alive
The classic use is a cache of objects that are expensive to create. A normal dictionary would keep every entry forever. A WeakValueDictionary keeps an entry only while some other part of the program still uses it.
import weakref
class Image:
def __init__(self, name):
self.name = name
cache = weakref.WeakValueDictionary()
def load(name):
image = cache.get(name)
if image is None:
image = Image(name)
cache[name] = image
return image
a = load("logo.png")
b = load("logo.png")
print(a is b) # True: the second call reused the cached object
print(len(cache)) # 1
del a, b
print(len(cache)) # 0 in CPython: no strong references remainNotice that load stores the result in the local name image before returning it. That avoids the check-then-use race from earlier.
Attaching data to objects you do not own
WeakKeyDictionary lets you store extra data about an object without changing the object's class and without extending its lifetime. The keys must be hashable and weakly referenceable.
import weakref
class Session:
pass
metadata = weakref.WeakKeyDictionary()
s = Session()
metadata[s] = {"requests": 3}
print(len(metadata)) # 1
del s
print(len(metadata)) # 0 in CPythonObservers with WeakSet
A subject that notifies listeners should not keep them alive. If it stored them in a normal list, a listener that the rest of the program had discarded would stay in memory and keep receiving events.
import weakref
class Listener:
def __init__(self, name):
self.name = name
def notify(self, event):
print(self.name, "got", event)
class Subject:
def __init__(self):
self._listeners = weakref.WeakSet()
def subscribe(self, listener):
self._listeners.add(listener)
def publish(self, event):
for listener in list(self._listeners):
listener.notify(event)
subject = Subject()
keep = Listener("keep")
drop = Listener("drop")
subject.subscribe(keep)
subject.subscribe(drop)
del drop
subject.publish("ping") # only "keep got ping"The loop iterates over list(self._listeners). That makes a snapshot of strong references, so a listener freed mid-loop cannot change the set while you iterate.
Bound methods and WeakMethod
A bound method such as obj.method is created fresh each time you access it. It holds a strong reference to obj. A weak reference to a bound method therefore points at a short-lived temporary and dies at once.
import weakref
class Handler:
def handle(self):
return "handled"
h = Handler()
broken = weakref.ref(h.handle)
print(broken()) # None: the temporary bound method was freed immediately
good = weakref.WeakMethod(h.handle)
print(good()()) # handled
del h
print(good()) # None: the instance is gone, so the method is deadWeakMethod stores weak references to the instance and to the underlying function, and rebuilds the bound method when you call it. Use it for callbacks that should not keep their owner alive.
Proxies
weakref.proxy(obj) returns an object that forwards attribute access to the target, so you do not need to call it. Once the target is freed, any use raises ReferenceError.
import weakref
class Resource:
def ping(self):
return "pong"
obj = Resource()
p = weakref.proxy(obj)
print(p.ping()) # pong
del obj
try:
p.ping()
except ReferenceError as exc:
print("proxy is dead:", exc)Proxies are convenient but hide the weak nature of the link, and a ReferenceError can surface far from where the object died. A plain ref with an explicit None check is usually clearer.
Cleanup with weakref.finalize
A callback on a bare ref only runs while that ref object survives. weakref.finalize solves this. It keeps itself registered until it runs, and it runs at most once. By default it also runs at interpreter exit if the object is still alive.
import weakref
class TempFile:
def __init__(self, path):
self.path = path
self._finalizer = weakref.finalize(self, print, "removing", path)
def close(self):
self._finalizer() # runs the cleanup now, at most once
f = TempFile("/tmp/demo")
del f # prints: removing /tmp/demoThe function and arguments you pass to finalize must not refer to the object, or the finalizer would hold a strong reference and the object could never be freed. That is why the example passes path, not self. finalize is generally safer than __del__, because it does not depend on the object being resurrectable and it behaves predictably at shutdown.
Breaking cycles with weak references
A weak reference can replace one direction of a cycle, so reference counting frees the structure without waiting for the cyclic collector. A tree where children point back at their parent is the usual case.
import weakref
class TreeNode:
def __init__(self, name, parent=None):
self.name = name
self.children = []
self._parent = weakref.ref(parent) if parent is not None else None
@property
def parent(self):
return self._parent() if self._parent is not None else None
root = TreeNode("root")
child = TreeNode("child", root)
root.children.append(child)
print(child.parent.name) # rootThe parent owns its children strongly. Each child points back weakly. When root is dropped, its count reaches zero immediately, with no cycle left to collect.
Common mistakes
- Taking a weak reference to the only copy of an object. The object is freed at once and the reference returns
Noneon the first call. - Weakly referencing a bound method instead of using
WeakMethod. - Adding
__slots__and then gettingTypeError: cannot create weak referencebecause__weakref__was left out. - Having a
finalizecallback or arefcallback capture the object, which keeps it alive forever. - Expecting a
WeakValueDictionaryto shrink in the middle of iteration. Iterate overlist(d.items())if entries could vanish during the loop.
Exercise
A function stores weakref.ref(obj.method) to call later, but the stored reference always returns None even though obj is still alive. Why does this happen, and what should the function store instead?
Show answer
Accessing obj.method creates a new bound method object each time. Only the weak reference points at that temporary object, so its count reaches zero as soon as the expression finishes, and it is freed. The function should store weakref.WeakMethod(obj.method). That keeps weak references to the instance and the function, and rebuilds the bound method when called.
Exercise
You build a WeakValueDictionary cache and fill it with cache["a"] = [1, 2, 3]. A TypeError is raised. What is the cause, and what is one way to fix it?
Show answer
Plain list objects cannot be weakly referenced, because they have no slot for weak references. Wrap the data in a class instance, or use a small subclass such as class Items(list): pass, and store an instance of that. Subclasses of list support weak references.