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

Skip to content

Commit 0fe5f25

Browse files
committed
Reset style values on any error.
1 parent 636241c commit 0fe5f25

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

lib/matplotlib/style/core.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,11 @@ def use(style):
7777
try:
7878
rc = rc_params_from_file(style, use_default_template=False)
7979
mpl.rcParams.update(rc)
80-
except:
80+
except IOError:
8181
msg = ("'%s' not found in the style library and input is "
8282
"not a valid URL or path. See `style.available` for "
8383
"list of available styles.")
84-
raise ValueError(msg % style)
84+
raise IOError(msg % style)
8585

8686

8787
@contextlib.contextmanager
@@ -111,9 +111,16 @@ def context(style, after_reset=False):
111111
initial_settings = mpl.rcParams.copy()
112112
if after_reset:
113113
mpl.rcdefaults()
114-
use(style)
115-
yield
116-
mpl.rcParams.update(initial_settings)
114+
try:
115+
use(style)
116+
except:
117+
# Restore original settings before raising any errors during the update.
118+
mpl.rcParams.update(initial_settings)
119+
raise
120+
else:
121+
yield
122+
finally:
123+
mpl.rcParams.update(initial_settings)
117124

118125

119126
def load_base_library():

lib/matplotlib/tests/test_style.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
unicode_literals)
33

44
import os
5+
import sys
56
import shutil
67
import tempfile
78
from contextlib import contextmanager
@@ -12,6 +13,7 @@
1213

1314
import six
1415

16+
from nose.tools import assert_raises
1517

1618
PARAM = 'image.cmap'
1719
VALUE = 'pink'
@@ -115,6 +117,22 @@ def test_context_with_union_of_dict_and_namedstyle():
115117
assert mpl.rcParams[other_param] == (not other_value)
116118

117119

120+
def test_context_with_badparam():
121+
if sys.version_info[:2] >= (2, 7):
122+
from collections import OrderedDict
123+
else:
124+
msg = "Test can only be run in Python >= 2.7 as it requires OrderedDict"
125+
raise SkipTest(msg)
126+
127+
original_value = 'gray'
128+
other_value = 'blue'
129+
d = OrderedDict([(PARAM, original_value), ('badparam', None)])
130+
with style.context({PARAM: other_value}):
131+
assert mpl.rcParams[PARAM] == other_value
132+
x = style.context([d])
133+
assert_raises(KeyError, x.__enter__)
134+
assert mpl.rcParams[PARAM] == other_value
135+
118136
if __name__ == '__main__':
119137
from numpy import testing
120138
testing.run_module_suite()

0 commit comments

Comments
 (0)