Skip to content

Commit 001b1e9

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``
1 parent 7722bab commit 001b1e9

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

lib/matplotlib/__init__.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -1247,10 +1247,16 @@ def __init__(self, rc=None, fname=None):
12471247
self.rcdict = rc
12481248
self.fname = fname
12491249
self._rcparams = rcParams.copy()
1250-
if self.fname:
1251-
rc_file(self.fname)
1252-
if self.rcdict:
1253-
rcParams.update(self.rcdict)
1250+
try:
1251+
if self.fname:
1252+
rc_file(self.fname)
1253+
if self.rcdict:
1254+
rcParams.update(self.rcdict)
1255+
except:
1256+
# if anything goes wrong, revert rc parameters and re-raise
1257+
rcParams.clear()
1258+
rcParams.update(self._rcparams)
1259+
raise
12541260

12551261
def __enter__(self):
12561262
return self

lib/matplotlib/tests/test_rcparams.py

+23
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from matplotlib.tests import assert_str_equal
1212
from matplotlib.testing.decorators import cleanup, knownfailureif
1313
from nose.tools import assert_true, assert_raises, assert_equal
14+
from nose.plugins.skip import SkipTest
1415
import nose
1516
from itertools import chain
1617
import numpy as np
@@ -253,3 +254,25 @@ def test_keymaps():
253254
key_list = [k for k in mpl.rcParams if 'keymap' in k]
254255
for k in key_list:
255256
assert(isinstance(mpl.rcParams[k], list))
257+
258+
259+
def test_rcparams_reset_after_fail():
260+
261+
# There was previously a bug that meant that if rc_context failed and
262+
# raised an exception due to issues in the supplied rc parameters, the
263+
# global rc parameters were left in a modified state.
264+
265+
if sys.version_info[:2] >= (2, 7):
266+
from collections import OrderedDict
267+
else:
268+
raise SkipTest("Test can only be run in Python >= 2.7 as it requires OrderedDict")
269+
270+
with mpl.rc_context(rc={'text.usetex': False}):
271+
272+
assert mpl.rcParams['text.usetex'] is False
273+
274+
with assert_raises(KeyError):
275+
with mpl.rc_context(rc=OrderedDict([('text.usetex', True),('test.blah', True)])):
276+
pass
277+
278+
assert mpl.rcParams['text.usetex'] is False

0 commit comments

Comments
 (0)