@@ -1259,44 +1259,39 @@ def use(backend, warn=False, force=True):
12591259 or a string of the form: ``module://my.module.name``.
12601260
12611261 warn : bool, optional, default: False
1262- If True and not *force*, warn that the call will have no effect if
1263- this is called after pyplot has been imported and a backend is set up .
1262+ If True and not *force*, emit a warning if a failure-to-switch
1263+ `ImportError` has been suppressed .
12641264
12651265 force : bool, optional, default: True
1266- If True, attempt to switch the backend. An ImportError is raised if
1267- an interactive backend is selected, but another interactive
1268- backend has already started.
1266+ If True (the default), raise an `ImportError` if the backend cannot be
1267+ set up (either because it fails to import, or because an incompatible
1268+ GUI interactive framework is already running); if False, ignore the
1269+ failure.
12691270
12701271 See Also
12711272 --------
12721273 :ref:`backends`
12731274 matplotlib.get_backend
12741275 """
12751276 name = validate_backend (backend )
1276-
12771277 if dict .__getitem__ (rcParams , 'backend' ) == name :
12781278 # Nothing to do if the requested backend is already set
12791279 pass
1280- elif 'matplotlib.pyplot' in sys .modules :
1281- # pyplot has already been imported (which triggered backend selection)
1282- # and the requested backend is different from the current one.
1283- if force :
1284- # if we are going to force switching the backend, pull in
1285- # `switch_backend` from pyplot (which is already imported).
1286- from matplotlib .pyplot import switch_backend
1287- switch_backend (name )
1288- elif warn :
1289- # Only if we are not going to force the switch *and* warn is True,
1290- # then direct users to `plt.switch_backend`.
1291- cbook ._warn_external (
1292- "matplotlib.pyplot has already been imported, "
1293- "this call will have no effect." )
12941280 else :
1295- # Finally if pyplot is not imported update both rcParams and
1296- # rcDefaults so restoring the defaults later with rcdefaults
1297- # won't change the backend. This is a bit of overkill as 'backend'
1298- # is already in style.core.STYLE_BLACKLIST, but better to be safe.
1281+ # Update both rcParams and rcDefaults so restoring the defaults later
1282+ # with rcdefaults won't change the backend. This is a bit of overkill
1283+ # as ' backend' is already in style.core.STYLE_BLACKLIST, but better to
1284+ # be safe.
12991285 rcParams ['backend' ] = rcParamsDefault ['backend' ] = name
1286+ try :
1287+ from matplotlib import pyplot as plt
1288+ plt .switch_backend (name )
1289+ except ImportError as exc :
1290+ if force :
1291+ raise
1292+ if warn :
1293+ cbook ._warn_external (
1294+ f"Failed to switch backend to { backend } : { exc } " )
13001295
13011296
13021297if os .environ .get ('MPLBACKEND' ):
0 commit comments