Skip to content

[Bug]: Weakly held listener garbage-collected inside CallbackRegistry.blocked() raises KeyError in _remove_proxy #32674

Backlog

Description

@pzeiger

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() replaces self.callbacks with {}, or a copy without the blocked signal, and restores the original on exit. _remove_proxy finds the listener's cid in self._func_cid_map, which blocked() leaves in place, then runs del self.callbacks[signal][cid] on the swapped dict. Afterwards the cid is gone from _func_cid_map, but a dead weakref stays in the restored callbacks[signal].
  • This happens in normal use. matplotlib opens norm.callbacks.blocked() itself:
    • in Colorbar._mesh, on every colorbar redraw;
    • in Normalize.autoscale and in ContourSet;
    • up to 3.9, in AxesImage._make_image, on every image draw.
  • 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 with filterwarnings = error, this gives an intermittent PytestUnraisableExceptionWarning that 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() is cbook.py:308-330 in 3.8.4 and cbook.py:400-422 in 3.11.2; _remove_proxy is cbook.py:241-258 and cbook.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 swaps self.callbacks, so one way to fix it is for _remove_proxy to tolerate the swap (e.g. self.callbacks.get(signal, {}).pop(cid, None)); that stops the exception but still restores the dead weakref on exit. Having blocked() 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions