Skip to content

swev-id: matplotlib__matplotlib-23299 Preserve figures when resolving auto backend#27

Open
casey-brooks wants to merge 1 commit intomatplotlib__matplotlib-23299from
fix/get_backend-rc_context-gcf-23299
Open

swev-id: matplotlib__matplotlib-23299 Preserve figures when resolving auto backend#27
casey-brooks wants to merge 1 commit intomatplotlib__matplotlib-23299from
fix/get_backend-rc_context-gcf-23299

Conversation

@casey-brooks
Copy link

Summary

  • prevent RcParams.__getitem__("backend") from clearing existing figures when rcParams['backend'] is the auto sentinel and pyplot already picked a backend
  • capture the active backend from matplotlib.backends.backend instead of re-invoking switch_backend() in that state
  • add a subprocess regression test that reproduces the original Gcf.figs clearing and now verifies the figures remain registered

Reproduction Steps

import matplotlib.pyplot as plt
from matplotlib import get_backend, rc_context

with rc_context():
    plt.figure()

before = f"{id(plt._pylab_helpers.Gcf)} {plt._pylab_helpers.Gcf.figs!r}"
get_backend()
after = f"{id(plt._pylab_helpers.Gcf)} {plt._pylab_helpers.Gcf.figs!r}"

assert before == after, '\n' + before + '\n' + after

Observed Failure (pre-fix)

AssertionError:
94453354309744 OrderedDict([(1, <matplotlib.backends.backend_qt.FigureManagerQT object at 0x...>)])
94453354309744 OrderedDict()

The fix avoids calling switch_backend() once pyplot already resolved a backend, so the active figures stay intact. Fixes #25.

Testing

  • MPLBACKEND=Agg pytest lib/matplotlib/tests/test_backends_interactive.py -k get_backend_preserves_figures -vv

Testing Notes

  • Installed build tooling via nix profile add ... python310 pip gcc freetype pkg-config zlib gnumake
  • Created a virtualenv, installed editable Matplotlib, and pulled in requirements/testing/all.txt
  • Downgraded numpy to 1.26.4 and pyparsing to 3.1.1 per project guidance
  • Set LD_LIBRARY_PATH to include the Nix GCC runtime libraries before running pytest

@casey-brooks casey-brooks requested a review from a team December 24, 2025 19:50
@casey-brooks
Copy link
Author

Test & Lint Summary

  • MPLBACKEND=Agg pytest lib/matplotlib/tests/test_backends_interactive.py -k get_backend_preserves_figures -vv (1 passed, 0 failed, 0 skipped)
  • flake8 lib/matplotlib/__init__.py lib/matplotlib/tests/test_backends_interactive.py (no issues)

Copy link

@noa-lucent noa-lucent left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look good. Thanks!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants