Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bc00dc9

Browse files
committed
Fixed a bug that caused rc parameters to not be reset to initial state if an exception happened while setting new rc parameters inside rc_context.
1 parent e0020d3 commit bc00dc9

2 files changed

Lines changed: 31 additions & 4 deletions

File tree

lib/matplotlib/__init__.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1249,10 +1249,15 @@ def __init__(self, rc=None, fname=None):
12491249
self.rcdict = rc
12501250
self.fname = fname
12511251
self._rcparams = rcParams.copy()
1252-
if self.fname:
1253-
rc_file(self.fname)
1254-
if self.rcdict:
1255-
rcParams.update(self.rcdict)
1252+
try:
1253+
if self.fname:
1254+
rc_file(self.fname)
1255+
if self.rcdict:
1256+
rcParams.update(self.rcdict)
1257+
except:
1258+
# if anything goes wrong, revert rc parameters and re-raise
1259+
rcParams.update(self._rcparams)
1260+
raise
12561261

12571262
def __enter__(self):
12581263
return self

lib/matplotlib/tests/test_rcparams.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,3 +262,25 @@ def test_keymaps():
262262
key_list = [k for k in mpl.rcParams if 'keymap' in k]
263263
for k in key_list:
264264
assert(isinstance(mpl.rcParams[k], list))
265+
266+
267+
def test_rcparams_reset_after_fail():
268+
269+
# There was previously a bug that meant that if rc_context failed and
270+
# raised an exception due to issues in the supplied rc parameters, the
271+
# global rc parameters were left in a modified state.
272+
273+
try:
274+
from collections import OrderedDict
275+
except:
276+
return # can't run this test on Python 2.6
277+
278+
with mpl.rc_context(rc={'text.usetex': False}):
279+
280+
assert mpl.rcParams['text.usetex'] is False
281+
282+
with assert_raises(KeyError):
283+
with mpl.rc_context(rc=OrderedDict([('text.usetex', True),('test.blah', True)])):
284+
pass
285+
286+
assert mpl.rcParams['text.usetex'] is False

0 commit comments

Comments
 (0)