From 8207bed89172af548d72535aa3965caf8117661a Mon Sep 17 00:00:00 2001 From: Casey Brooks Date: Wed, 24 Dec 2025 19:49:30 +0000 Subject: [PATCH] fix(rcparams): preserve figures for get_backend #25 --- lib/matplotlib/__init__.py | 5 ++++ .../tests/test_backends_interactive.py | 27 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index c268a56724c9..093e806cd9c6 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -674,7 +674,12 @@ def __getitem__(self, key): val = dict.__getitem__(self, key) if val is rcsetup._auto_backend_sentinel: from matplotlib import pyplot as plt + if plt._backend_mod is not None: + import matplotlib.backends + return matplotlib.backends.backend plt.switch_backend(rcsetup._auto_backend_sentinel) + return dict.__getitem__(self, key) + return val return dict.__getitem__(self, key) diff --git a/lib/matplotlib/tests/test_backends_interactive.py b/lib/matplotlib/tests/test_backends_interactive.py index 9e920e33d355..b7243eae7f99 100644 --- a/lib/matplotlib/tests/test_backends_interactive.py +++ b/lib/matplotlib/tests/test_backends_interactive.py @@ -270,6 +270,33 @@ def test_lazy_auto_backend_selection(): timeout=_test_timeout) +def _impl_get_backend_preserves_figures(): + import matplotlib + from matplotlib import get_backend, rc_context, rcsetup + from matplotlib import pyplot as plt + + plt.close("all") + matplotlib.rcParams["backend"] = rcsetup._auto_backend_sentinel + + with rc_context(): + plt.figure() + + matplotlib.rcParams["backend"] = rcsetup._auto_backend_sentinel + assert plt._backend_mod is not None + + gcf = plt._pylab_helpers.Gcf + assert tuple(gcf.figs.items()) + before = (id(gcf), tuple(gcf.figs.items())) + get_backend() + after = (id(gcf), tuple(gcf.figs.items())) + assert before == after + + +def test_get_backend_preserves_figures(): + _run_helper(_impl_get_backend_preserves_figures, + timeout=_test_timeout) + + def _implqt5agg(): import matplotlib.backends.backend_qt5agg # noqa import sys