@@ -1136,16 +1136,34 @@ def use(backend, *, force=True):
1136
1136
matplotlib.get_backend
1137
1137
"""
1138
1138
name = validate_backend (backend )
1139
+ # we need to use the base-class method here to avoid (prematurely)
1140
+ # resolving the "auto" backend setting
1139
1141
if dict .__getitem__ (rcParams , 'backend' ) == name :
1140
1142
# Nothing to do if the requested backend is already set
1141
1143
pass
1142
1144
else :
1143
- try :
1144
- from matplotlib import pyplot as plt
1145
- plt .switch_backend (name )
1146
- except ImportError :
1147
- if force :
1148
- raise
1145
+ # if pyplot is not already imported, do not import it. Doing
1146
+ # so may trigger a `plt.switch_backend` to the _default_ backend
1147
+ # before we get a chance to change to the one the user just requested
1148
+ plt = sys .modules .get ('matplotlib.pyplot' )
1149
+ # if pyplot is imported, then try to change backends
1150
+ if plt is not None :
1151
+ try :
1152
+ # we need this import check here to re-raise if the
1153
+ # user does not have the libraries to support their
1154
+ # chosen backend installed.
1155
+ plt .switch_backend (name )
1156
+ except ImportError :
1157
+ if force :
1158
+ raise
1159
+ # if we have not imported pyplot, then we can set the rcParam
1160
+ # value which will be respected when the user finally imports
1161
+ # pyplot
1162
+ else :
1163
+ rcParams ['backend' ] = backend
1164
+ # if the user has asked for a given backend, do not helpfully
1165
+ # fallback
1166
+ rcParams ['backend_fallback' ] = False
1149
1167
1150
1168
1151
1169
if os .environ .get ('MPLBACKEND' ):
0 commit comments