Skip to content

Commit b656279

Browse files
committed
MNT: Remove internal usage of the 'backend' key in rcParams
1 parent 1849379 commit b656279

3 files changed

Lines changed: 25 additions & 29 deletions

File tree

‎lib/matplotlib/__init__.py‎

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -799,18 +799,21 @@ def __setitem__(self, key, val):
799799

800800
def __getitem__(self, key):
801801
if key == "backend":
802-
# In theory, this should only ever be used after the global rcParams
803-
# has been set up, but better be safe e.g. in presence of breakpoints.
804-
if (self is globals().get("rcParams")
805-
and RcParams._backend is rcsetup._auto_backend_sentinel):
806-
from matplotlib import pyplot as plt
807-
plt.switch_backend(rcsetup._auto_backend_sentinel)
808-
return RcParams._backend
802+
return self._get_backend_resolved()
809803
return self._get(key)
810804

811-
def _get_backend_or_none(self):
812-
"""Get the requested backend, if any, without triggering resolution."""
813-
backend = RcParams._backend
805+
@classmethod
806+
def _get_backend_resolved(cls):
807+
"""Get the backend, resolving the auto-sentinel if needed."""
808+
if cls._backend is rcsetup._auto_backend_sentinel:
809+
from matplotlib import pyplot as plt
810+
plt.switch_backend(rcsetup._auto_backend_sentinel)
811+
return cls._backend
812+
813+
@classmethod
814+
def _get_backend_or_none(cls):
815+
"""Get the current backend or None."""
816+
backend = cls._backend
814817
return None if backend is rcsetup._auto_backend_sentinel else backend
815818

816819
def __repr__(self):
@@ -1292,14 +1295,14 @@ def use(backend, *, force=True):
12921295
# value which will be respected when the user finally imports
12931296
# pyplot
12941297
else:
1295-
rcParams['backend'] = backend
1298+
rcParams._backend = backend
12961299
# if the user has asked for a given backend, do not helpfully
12971300
# fallback
12981301
rcParams['backend_fallback'] = False
12991302

13001303

13011304
if os.environ.get('MPLBACKEND'):
1302-
rcParams['backend'] = os.environ.get('MPLBACKEND')
1305+
rcParams._backend = os.environ.get('MPLBACKEND')
13031306

13041307

13051308
def get_backend(*, auto_select=True):
@@ -1326,13 +1329,9 @@ def get_backend(*, auto_select=True):
13261329
matplotlib.use
13271330
"""
13281331
if auto_select:
1329-
return rcParams['backend']
1332+
return rcParams._get_backend_resolved()
13301333
else:
1331-
backend = rcParams._get('backend')
1332-
if backend is rcsetup._auto_backend_sentinel:
1333-
return None
1334-
else:
1335-
return backend
1334+
return rcParams._get_backend_or_none()
13361335

13371336

13381337
def interactive(b):

‎lib/matplotlib/pyplot.py‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
FigureCanvasBase, FigureManagerBase, MouseButton)
7474
from matplotlib.figure import Figure, FigureBase, figaspect
7575
from matplotlib.gridspec import GridSpec, SubplotSpec
76-
from matplotlib import rcsetup, rcParamsDefault, rcParamsOrig
76+
from matplotlib import rcsetup
7777
from matplotlib.artist import Artist
7878
from matplotlib.axes import Axes
7979
from matplotlib.axes import Subplot # noqa: F401
@@ -385,10 +385,10 @@ def _get_backend_mod() -> type[matplotlib.backend_bases._Backend]:
385385
This is currently private, but may be made public in the future.
386386
"""
387387
if _backend_mod is None:
388-
# Use rcParams._get("backend") to avoid going through the fallback
388+
# Use rcParams._backend to avoid going through the fallback
389389
# logic (which will (re)import pyplot and then call switch_backend if
390390
# we need to resolve the auto sentinel)
391-
switch_backend(rcParams._get("backend"))
391+
switch_backend(rcParams._backend)
392392
return cast(type[matplotlib.backend_bases._Backend], _backend_mod)
393393

394394

@@ -432,16 +432,13 @@ def switch_backend(newbackend: str) -> None:
432432
_log.debug("Skipping backend candidate %r as loading failed.",
433433
candidate, exc_info=True)
434434
continue
435-
else:
436-
rcParamsOrig['backend'] = candidate
437-
return
435+
return
438436
else:
439437
# Switching to Agg should always succeed; if it doesn't, let the
440438
# exception propagate out.
441439
switch_backend("agg")
442-
rcParamsOrig["backend"] = "agg"
443440
return
444-
old_backend = rcParams._get('backend') # get without triggering backend resolution
441+
old_backend = rcParams._backend
445442

446443
module = backend_registry.load_backend_module(newbackend)
447444
canvas_class = module.FigureCanvas
@@ -530,7 +527,7 @@ def draw_if_interactive() -> None:
530527
except im.PackageNotFoundError:
531528
pass
532529

533-
rcParams['backend'] = rcParamsDefault['backend'] = newbackend
530+
rcParams._backend = newbackend
534531
_backend_mod = backend_mod
535532
for func_name in ["new_figure_manager", "draw_if_interactive", "show"]:
536533
globals()[func_name].__signature__ = inspect.signature(

‎lib/matplotlib/tests/test_backends_interactive.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def _test_interactive_impl():
168168
})
169169

170170
mpl.rcParams.update(json.loads(sys.argv[1]))
171-
backend = plt.rcParams["backend"].lower()
171+
backend = plt.rcParams.get_backend_resolved().lower()
172172

173173
if backend.endswith("agg") and not backend.startswith(("gtk", "web")):
174174
# Force interactive framework setup.
@@ -296,7 +296,7 @@ def _test_thread_impl():
296296
# the figure
297297
canvas = fig.canvas
298298
plt.close() # backend is responsible for flushing any events here
299-
if plt.rcParams["backend"].lower().startswith("wx"):
299+
if plt.rcParams._get_backend_resolved().lower().startswith("wx"):
300300
# TODO: debug why WX needs this only on py >= 3.8
301301
canvas.flush_events()
302302

0 commit comments

Comments
 (0)