@@ -1248,44 +1248,39 @@ def use(backend, warn=False, force=True):
12481248 or a string of the form: ``module://my.module.name``.
12491249
12501250 warn : bool, optional, default: False
1251- If True and not *force*, warn that the call will have no effect if
1252- this is called after pyplot has been imported and a backend is set up .
1251+ If True and not *force*, emit a warning if a failure-to-switch
1252+ `ImportError` has been suppressed .
12531253
12541254 force : bool, optional, default: True
1255- If True, attempt to switch the backend. An ImportError is raised if
1256- an interactive backend is selected, but another interactive
1257- backend has already started.
1255+ If True (the default), raise an `ImportError` if the backend cannot be
1256+ set up (either because it fails to import, or because an incompatible
1257+ GUI interactive framework is already running); if False, ignore the
1258+ failure.
12581259
12591260 See Also
12601261 --------
12611262 :ref:`backends`
12621263 matplotlib.get_backend
12631264 """
12641265 name = validate_backend (backend )
1265-
12661266 if dict .__getitem__ (rcParams , 'backend' ) == name :
12671267 # Nothing to do if the requested backend is already set
12681268 pass
1269- elif 'matplotlib.pyplot' in sys .modules :
1270- # pyplot has already been imported (which triggered backend selection)
1271- # and the requested backend is different from the current one.
1272- if force :
1273- # if we are going to force switching the backend, pull in
1274- # `switch_backend` from pyplot (which is already imported).
1275- from matplotlib .pyplot import switch_backend
1276- switch_backend (name )
1277- elif warn :
1278- # Only if we are not going to force the switch *and* warn is True,
1279- # then direct users to `plt.switch_backend`.
1280- cbook ._warn_external (
1281- "matplotlib.pyplot has already been imported, "
1282- "this call will have no effect." )
12831269 else :
1284- # Finally if pyplot is not imported update both rcParams and
1285- # rcDefaults so restoring the defaults later with rcdefaults
1286- # won't change the backend. This is a bit of overkill as 'backend'
1287- # is already in style.core.STYLE_BLACKLIST, but better to be safe.
1270+ # Update both rcParams and rcDefaults so restoring the defaults later
1271+ # with rcdefaults won't change the backend. This is a bit of overkill
1272+ # as ' backend' is already in style.core.STYLE_BLACKLIST, but better to
1273+ # be safe.
12881274 rcParams ['backend' ] = rcParamsDefault ['backend' ] = name
1275+ try :
1276+ from matplotlib import pyplot as plt
1277+ plt .switch_backend (name )
1278+ except ImportError as exc :
1279+ if force :
1280+ raise
1281+ if warn :
1282+ cbook ._warn_external (
1283+ f"Failed to switch backend to { backend } : { exc } " )
12891284
12901285
12911286if os .environ .get ('MPLBACKEND' ):
0 commit comments