Repository navigation
Description
Bug summary
When a weakly held listener of a CallbackRegistry is garbage-collected inside blocked(), _remove_proxy raises an unraisable KeyError and leaves a dead weakref in the registry. The cause is that blocked() swaps self.callbacks for the duration of the block, and _remove_proxy deletes from the swapped dict.
Code for reproduction
import gc
import sys
from matplotlib import colors
caught = []
sys.unraisablehook = lambda u: caught.append(repr(u.exc_value))
class Listener:
def __init__(self):
self.me = self # reference cycle: only the cyclic collector frees it
def on_changed(self):
pass
norm = colors.Normalize(0, 1)
listener = Listener()
norm.callbacks.connect("changed", listener.on_changed) # held as a weak method
del listener
gc.disable()
with norm.callbacks.blocked():
gc.collect() # stands in for an automatic collection inside the block
gc.enable()
print("unraisable:", caught)
print("callbacks after:", norm.callbacks.callbacks)Actual outcome
unraisable: ["KeyError('changed')"]
callbacks after: {'changed': {0: <weakref at 0x...; dead>}}
Without the sys.unraisablehook line, Python prints Exception ignored in: <function WeakMethod.__new__.<locals>._cb ...> with a traceback ending in del self.callbacks[signal][cid] / KeyError: 'changed'.
Expected outcome
No exception, and the dead listener removed from the registry, as when it is collected outside a blocked() block.
Additional information
- Mechanism:
blocked()replacesself.callbackswith{}, or a copy without the blocked signal, and restores the original on exit._remove_proxyfinds the listener's cid inself._func_cid_map, whichblocked()leaves in place, then runsdel self.callbacks[signal][cid]on the swapped dict. Afterwards the cid is gone from_func_cid_map, but a dead weakref stays in the restoredcallbacks[signal]. - This happens in normal use. matplotlib opens
norm.callbacks.blocked()itself:- in
Colorbar._mesh, on every colorbar redraw; - in
Normalize.autoscaleand inContourSet; - up to 3.9, in
AxesImage._make_image, on every image draw.
- in
- A listener freed only by the cyclic collector is collected at whatever allocation triggers the collector, which can be inside one of those blocks. One example is a colorbar's replaced
QuadMesh, kept in a cycle through a mathtext label's parse traceback. Under pytest withfilterwarnings = error, this gives an intermittentPytestUnraisableExceptionWarningthat depends on test order. - Same result on matplotlib 3.8.4, 3.9.0, 3.9.4, 3.10.0, 3.10.8, 3.11.0, 3.11.2 and the nightly wheel 3.12.0.dev958+gd3f6ddf27.
- Line numbers:
blocked()iscbook.py:308-330in 3.8.4 andcbook.py:400-422in 3.11.2;_remove_proxyiscbook.py:241-258andcbook.py:324-335; the raising line is 248 and 330. - Signals are not lost:
process()skips the dead weakref left behind, so the only lasting effect is that entry, one per occurrence. blocked()only swapsself.callbacks, so one way to fix it is for_remove_proxyto tolerate the swap (e.g.self.callbacks.get(signal, {}).pop(cid, None)); that stops the exception but still restores the dead weakref on exit. Havingblocked()record removals made while it is active and apply them to the original dict on exit would remove that too.
🤖 Written by Claude Code — Paul reviewed and posted it
Operating system
Linux (Ubuntu 24.04)
Matplotlib Version
3.8.4 to 3.11.2, and 3.12.0.dev958+gd3f6ddf27
Matplotlib Backend
Agg
Python version
3.11 (with 3.8.4), 3.12 (with 3.11.2)
Jupyter version
No response
Installation
pip
Activity