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

Skip to content

Commit 112f199

Browse files
committed
Merge pull request #3752 from astrofrog/rc_context_exceptions
BUG : Make sure that initial state gets reset if anything goes wrong in ``rc_context``
2 parents e0020d3 + 39c3194 commit 112f199

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

lib/matplotlib/__init__.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1249,10 +1249,16 @@ 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.clear()
1260+
rcParams.update(self._rcparams)
1261+
raise
12561262

12571263
def __enter__(self):
12581264
return self

lib/matplotlib/tests/test_rcparams.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from matplotlib.tests import assert_str_equal
1313
from matplotlib.testing.decorators import cleanup, knownfailureif
1414
from nose.tools import assert_true, assert_raises, assert_equal
15+
from nose.plugins.skip import SkipTest
1516
import nose
1617
from itertools import chain
1718
import numpy as np
@@ -262,3 +263,25 @@ def test_keymaps():
262263
key_list = [k for k in mpl.rcParams if 'keymap' in k]
263264
for k in key_list:
264265
assert(isinstance(mpl.rcParams[k], list))
266+
267+
268+
def test_rcparams_reset_after_fail():
269+
270+
# There was previously a bug that meant that if rc_context failed and
271+
# raised an exception due to issues in the supplied rc parameters, the
272+
# global rc parameters were left in a modified state.
273+
274+
if sys.version_info[:2] >= (2, 7):
275+
from collections import OrderedDict
276+
else:
277+
raise SkipTest("Test can only be run in Python >= 2.7 as it requires OrderedDict")
278+
279+
with mpl.rc_context(rc={'text.usetex': False}):
280+
281+
assert mpl.rcParams['text.usetex'] is False
282+
283+
with assert_raises(KeyError):
284+
with mpl.rc_context(rc=OrderedDict([('text.usetex', True),('test.blah', True)])):
285+
pass
286+
287+
assert mpl.rcParams['text.usetex'] is False

0 commit comments

Comments
 (0)