diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 23643a53d811..47f1f4a6d0ed 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -1296,15 +1296,35 @@ def use(backend, *, force=True): rcParams['backend'] = os.environ.get('MPLBACKEND') -def get_backend(): +def get_backend(*, resolve=True): """ Return the name of the current backend. + Parameters + ---------- + resolve : bool, default: True + Whether to trigger backend resolution if no backend has been + selected so far. If True, this ensures that a valid backend + is returned. If False, this returns None if no backend has been + selected so far. + + .. admonition:: Provisional + + The *resolve* flag is provisional. It may be changed or removed + without prior warning. + See Also -------- matplotlib.use """ - return rcParams['backend'] + if resolve: + return rcParams['backend'] + else: + backend = rcParams._get('backend') + if backend is rcsetup._auto_backend_sentinel(): + return None + else: + return backend def interactive(b): diff --git a/lib/matplotlib/__init__.pyi b/lib/matplotlib/__init__.pyi index 5b6797d3a7da..9c1d1e560afd 100644 --- a/lib/matplotlib/__init__.pyi +++ b/lib/matplotlib/__init__.pyi @@ -37,7 +37,7 @@ import contextlib from packaging.version import Version from matplotlib._api import MatplotlibDeprecationWarning -from typing import Any, NamedTuple +from typing import Any, Literal, NamedTuple, overload class _VersionInfo(NamedTuple): major: int @@ -104,7 +104,10 @@ def rc_context( rc: dict[str, Any] | None = ..., fname: str | Path | os.PathLike | None = ... ) -> Generator[None, None, None]: ... def use(backend: str, *, force: bool = ...) -> None: ... -def get_backend() -> str: ... +@overload +def get_backend(*, resolve: Literal[True] = True) -> str: ... +@overload +def get_backend(*, resolve: Literal[False]) -> str | None: ... def interactive(b: bool) -> None: ... def is_interactive() -> bool: ... diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 0aa3ec0ba603..ef054f7492f0 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -554,6 +554,7 @@ def test_backend_fallback_headful(tmp_path): # Check that access on another instance does not resolve the sentinel. "assert mpl.RcParams({'backend': sentinel})['backend'] == sentinel; " "assert mpl.rcParams._get('backend') == sentinel; " + "assert mpl.get_backend(resolve=False) is None; " "import matplotlib.pyplot; " "print(matplotlib.get_backend())"], env=env, text=True, check=True, capture_output=True).stdout