137137
138138# cbook must import matplotlib only within function
139139# definitions, so it is safe to import from it here.
140- from . import cbook
140+ from . import cbook , rcsetup
141141from matplotlib .cbook import (
142142 MatplotlibDeprecationWarning , dedent , get_label , sanitize_sequence )
143143from matplotlib .cbook import mplDeprecation # deprecated
@@ -849,6 +849,10 @@ def __setitem__(self, key, val):
849849 cbook .warn_deprecated (
850850 "3.0" , "{} is deprecated; in the future, examples will be "
851851 "found relative to the 'datapath' directory." .format (key ))
852+ elif key == 'backend' :
853+ if val is rcsetup ._auto_backend_sentinel :
854+ if 'backend' in self :
855+ return
852856 try :
853857 cval = self .validate [key ](val )
854858 except ValueError as ve :
@@ -877,6 +881,12 @@ def __getitem__(self, key):
877881 "3.0" , "{} is deprecated; in the future, examples will be "
878882 "found relative to the 'datapath' directory." .format (key ))
879883
884+ elif key == "backend" :
885+ val = dict .__getitem__ (self , key )
886+ if val is rcsetup ._auto_backend_sentinel :
887+ from matplotlib import pyplot as plt
888+ plt .switch_backend (rcsetup ._auto_backend_sentinel )
889+
880890 return dict .__getitem__ (self , key )
881891
882892 def __repr__ (self ):
@@ -1091,10 +1101,10 @@ def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
10911101 _fullpath = os .path .join (_basedir , rcParams ['examples.directory' ])
10921102 rcParams ['examples.directory' ] = _fullpath
10931103
1094- rcParamsOrig = rcParams .copy ()
10951104
10961105with warnings .catch_warnings ():
10971106 warnings .simplefilter ("ignore" , MatplotlibDeprecationWarning )
1107+ rcParamsOrig = RcParams (rcParams .copy ())
10981108 rcParamsDefault = RcParams ([(key , default ) for key , (default , converter ) in
10991109 defaultParams .items ()
11001110 if key not in _all_deprecated ])
@@ -1218,7 +1228,7 @@ def rc_file_defaults():
12181228 with warnings .catch_warnings ():
12191229 warnings .simplefilter ("ignore" , mplDeprecation )
12201230 from .style .core import STYLE_BLACKLIST
1221- rcParams .update ({k : v for k , v in rcParamsOrig . items ()
1231+ rcParams .update ({k : rcParamsOrig [ k ] for k in rcParamsOrig
12221232 if k not in STYLE_BLACKLIST })
12231233
12241234
@@ -1234,7 +1244,8 @@ def rc_file(fname):
12341244 with warnings .catch_warnings ():
12351245 warnings .simplefilter ("ignore" , mplDeprecation )
12361246 from .style .core import STYLE_BLACKLIST
1237- rcParams .update ({k : v for k , v in rc_params_from_file (fname ).items ()
1247+ rc_from_file = rc_params_from_file (fname )
1248+ rcParams .update ({k : rc_from_file [k ] for k in rc_from_file
12381249 if k not in STYLE_BLACKLIST })
12391250
12401251
@@ -1285,16 +1296,23 @@ def __init__(self, rc=None, fname=None):
12851296 if rc :
12861297 rcParams .update (rc )
12871298 except Exception :
1288- # If anything goes wrong, revert to the original rcs.
1289- dict .update (rcParams , self ._orig )
1299+ self .__fallback ()
12901300 raise
12911301
1302+ def __fallback (self ):
1303+ # If anything goes wrong, revert to the original rcs.
1304+ updated_backend = self ._orig ['backend' ]
1305+ dict .update (rcParams , self ._orig )
1306+ # except for the backend. If the context block triggered resloving
1307+ # the auto backend resolution keep that value around
1308+ if self ._orig ['backend' ] is rcsetup ._auto_backend_sentinel :
1309+ rcParams ['backend' ] = updated_backend
1310+
12921311 def __enter__ (self ):
12931312 return self
12941313
12951314 def __exit__ (self , exc_type , exc_value , exc_tb ):
1296- # No need to revalidate the original values.
1297- dict .update (rcParams , self ._orig )
1315+ self .__fallback ()
12981316
12991317
13001318def use (arg , warn = True , force = False ):
@@ -1320,14 +1338,14 @@ def use(arg, warn=True, force=False):
13201338
13211339 force : bool, optional
13221340 If True, attempt to switch the backend. This defaults to
1323- false and using `.pyplot.switch_backend` is preferred .
1341+ False .
13241342
13251343
13261344 """
13271345 name = validate_backend (arg )
13281346
13291347 # if setting back to the same thing, do nothing
1330- if (rcParams [ 'backend' ] == name ):
1348+ if (dict . __getitem__ ( rcParams , 'backend' ) == name ):
13311349 pass
13321350
13331351 # Check if we have already imported pyplot and triggered
@@ -1357,7 +1375,7 @@ def use(arg, warn=True, force=False):
13571375
13581376
13591377if os .environ .get ('MPLBACKEND' ):
1360- use ( os .environ [ 'MPLBACKEND' ] )
1378+ rcParams [ 'backend' ] = os .environ . get ( 'MPLBACKEND' )
13611379
13621380
13631381def get_backend ():
0 commit comments