8000 Merge pull request #16684 from cool-RR/2020-03-05-raise-from · matplotlib/matplotlib@376b75d · GitHub
[go: up one dir, main page]

Skip to content

Commit 376b75d

Browse files
authored
Merge pull request #16684 from cool-RR/2020-03-05-raise-from
Fix exception causes in 19 modules
2 parents 4595bbd + c89ac3e commit 376b75d

File tree

19 files changed

+59
-51
lines changed

19 files changed

+59
-51
lines changed

lib/matplotlib/markers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,9 +287,9 @@ def set_marker(self, marker):
287287
try:
288288
Path(marker)
289289
self._marker_function = self._set_vertices
290-
except ValueError:
290+
except ValueError as err:
291291
raise ValueError('Unrecognized marker style {!r}'
292-
.format(marker))
292+
.format(marker)) from err
293293

294294
self._marker = marker
295295
self._recache()

lib/matplotlib/mathtext.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,10 @@ def get_unicode_index(symbol, math=True):
7373
pass
7474
try: # Is symbol a TeX symbol (i.e. \alpha)
7575
return tex2uni[symbol.strip("\\")]
76-
except KeyError:
76+
except KeyError as err:
7777
raise ValueError(
7878
"'{}' is not a valid Unicode character or TeX/Type1 symbol"
79-
.format(symbol))
79+
.format(symbol)) from err
8080

8181

8282
class MathtextBackend:
@@ -2616,7 +2616,7 @@ def parse(self, s, fonts_object, fontsize, dpi):
26162616
raise ValueError("\n".join(["",
26172617
err.line,
26182618
" " * (err.column - 1) + "^",
2619-
str(err)]))
2619+
str(err)])) from err
26202620
self._state_stack = None
26212621
self._em_width_cache = {}
26222622
self._expression.resetCache()
@@ -2731,8 +2731,9 @@ def symbol(self, s, loc, toks):
27312731
c = toks[0]
27322732
try:
27332733
char = Char(c, self.get_state())
2734-
except ValueError:
2735-
raise ParseFatalException(s, loc, "Unknown symbol: %s" % c)
2734+
except ValueError as err:
2735+
raise ParseFatalException(s, loc,
2736+
"Unknown symbol: %s" % c) from err
27362737

27372738
if c in self._spaced_symbols:
27382739
# iterate until we find previous character, needed for cases

lib/matplotlib/offsetbox.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1167,8 +1167,9 @@ def set_bbox_to_anchor(self, bbox, transform=None):
11671167
else:
11681168
try:
11691169
l = len(bbox)
1170-
except TypeError:
1171-
raise ValueError("Invalid argument for bbox : %s" % str(bbox))
1170+
except TypeError as err:
1171+
raise ValueError("Invalid argument for bbox : %s" %
1172+
str(bbox)) from err
11721173

11731174
if l == 2:
11741175
bbox = [bbox[0], bbox[1], 0, 0]

lib/matplotlib/patches.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1844,14 +1844,15 @@ def __new__(cls, stylename, **kw):
18441844
_name = _list[0].lower()
18451845
try:
18461846
_cls = cls._style_list[_name]
1847-
except KeyError:
1848-
raise ValueError("Unknown style : %s" % stylename)
1847+
except KeyError as err:
1848+
raise ValueError("Unknown style : %s" % stylename) from err
18491849

18501850
try:
18511851
_args_pair = [cs.split("=") for cs in _list[1:]]
18521852
_args = {k: float(v) for k, v in _args_pair}
1853-
except ValueError:
1854-
raise ValueError("Incorrect style argument : %s" % stylename)
1853+
except ValueError as err:
1854+
raise ValueError("Incorrect style argument : %s" %
1855+
stylename) from err
18551856
_args.update(kw)
18561857

18571858
return _cls(**_args)

lib/matplotlib/projections/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ def get_projection_class(projection=None):
5252

5353
try:
5454
return projection_registry.get_projection_class(projection)
55-
except KeyError:
56-
raise ValueError("Unknown projection %r" % projection)
55+
except KeyError as err:
56+
raise ValueError("Unknown projection %r" % projection) from err
5757

5858

5959
get_projection_names = projection_registry.get_projection_names

lib/matplotlib/pyplot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,9 @@ def uninstall_repl_displayhook():
155155
ip = get_ipython()
156156
try:
157157
ip.events.unregister('post_execute', _IP_REGISTERED)
158-
except AttributeError:
158+
except AttributeError as err:
159159
raise NotImplementedError("Can not unregister events "
160-
"in IPython < 2.0")
160+
"in IPython < 2.0") from err
161161
_IP_REGISTERED = None
162162

163163
if _INSTALL_FIG_OBSERVER:

lib/matplotlib/sphinxext/plot_directive.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -444,11 +444,11 @@ def run_code(code, code_path, ns=None, function_name=None):
444444
except OSError as err:
445445
raise OSError(str(err) + '\n`plot_working_directory` option in'
446446
'Sphinx configuration file must be a valid '
447-
'directory path')
447+
'directory path') from err
448448
except TypeError as err:
449449
raise TypeError(str(err) + '\n`plot_working_directory` option in '
450450
'Sphinx configuration file must be a string or '
451-
'None')
451+
'None') from err
452452
elif code_path is not None:
453453
dirname = os.path.abspath(os.path.dirname(code_path))
454454
os.chdir(dirname)
@@ -475,8 +475,8 @@ def run_code(code, code_path, ns=None, function_name=None):
475475
if function_name is not None:
476476
exec(function_name + "()", ns)
477477

478-
except (Exception, SystemExit):
479-
raise PlotError(traceback.format_exc())
478+
except (Exception, SystemExit) as err:
479+
raise PlotError(traceback.format_exc()) from err
480480
finally:
481481
os.chdir(pwd)
482482
return ns
@@ -600,8 +600,8 @@ def render_figures(code, code_path, output_dir, output_base, context,
600600
for fmt, dpi in formats:
601601
try:
602602
figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi)
603-
except Exception:
604-
raise PlotError(traceback.format_exc())
603+
except Exception as err:
604+
raise PlotError(traceback.format_exc()) from err
605605
img.formats.append(fmt)
606606

607607
results.append((code_piece, images))

lib/matplotlib/streamplot.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -372,8 +372,9 @@ class StreamMask:
372372
def __init__(self, density):
373373
try:
374374
self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int)
375-
except ValueError:
376-
raise ValueError("'density' must be a scalar or be of length 2")
375+
except ValueError as err:
376+
raise ValueError("'density' must be a scalar or be of length "
377+
"2") from err
377378
if self.nx < 0 or self.ny < 0:
378379
raise ValueError("'density' must be positive")
379380
self._mask = np.zeros((self.ny, self.nx))

lib/matplotlib/style/core.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,11 @@ def use(style):
114114
try:
115115
rc = rc_params_from_file(style, use_default_template=False)
116116
_apply_style(rc)
117-
except IOError:
117+
except IOError as err:
118118
raise IOError(
119119
"{!r} not found in the style library and input is not a "
120120
"valid URL or path; see `style.available` for list of "
121-
"available styles".format(style))
121+
"available styles".format(style)) from err
122122

123123

124124
@contextlib.contextmanager

lib/matplotlib/table.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -358,8 +358,9 @@ def __setitem__(self, position, cell):
358358
cbook._check_isinstance(CustomCell, cell=cell)
359359
try:
360360
row, col = position[0], position[1]
361-
except Exception:
362-
raise KeyError('Only tuples length 2 are accepted as coordinates')
361+
except Exception as err:
362+
raise KeyError('Only tuples length 2 are accepted as '
363+
'coordinates') from err
363364
cell.set_figure(self.figure)
364365
cell.set_transform(self.get_transform())
365366
cell.set_clip_on(False)

lib/matplotlib/testing/compare.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ def __call__(self, orig, dest):
127127
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
128128
try:
129129
self._read_until(b"\nGS")
130-
except _ConverterError:
131-
raise OSError("Failed to start Ghostscript")
130+
except _ConverterError as err:
131+
raise OSError("Failed to start Ghostscript") from err
132132

133133
def encode_and_escape(name):
134134
return (os.fsencode(name)
@@ -181,8 +181,9 @@ def __call__(self, orig, dest):
181181
self._proc.stderr = stderr
182182
try:
183183
self._read_until(b"\n>")
184-
except _ConverterError:
185-
raise OSError("Failed to start Inkscape in interactive mode")
184+
except _ConverterError as err:
185+
raise OSError("Failed to start Inkscape in interactive "
186+
"mode") from err
186187

187188
# Inkscape uses glib's `g_shell_parse_argv`, which has a consistent
188189
# behavior across platforms, so we can just use `shlex.quote`.
@@ -199,14 +200,14 @@ def __call__(self, orig, dest):
199200
self._proc.stdin.flush()
200201
try:
201202
self._read_until(b"\n>")
202-
except _ConverterError:
203+
except _ConverterError as err:
203204
# Inkscape's output is not localized but gtk's is, so the output
204205
# stream probably has a mixed encoding. Using the filesystem
205206
# encoding should at least get the filenames right...
206207
self._stderr.seek(0)
207208
raise ImageComparisonFailure(
208209
self._stderr.read().decode(
209-
sys.getfilesystemencoding(), "replace"))
210+
sys.getfilesystemencoding(), "replace")) from err
210211

211212

212213
def _update_converter():

lib/matplotlib/testing/decorators.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,10 +192,11 @@ def copy_baseline(self, baseline, extension):
192192
os.symlink(orig_expected_path, expected_fname)
193193
except OSError: # On Windows, symlink *may* be unavailable.
194194
shutil.copyfile(orig_expected_path, expected_fname)
195-
except OSError:
195+
except OSError as err:
196196
raise ImageComparisonFailure(
197197
f"Missing baseline image {expected_fname} because the "
198-
f"following file cannot be accessed: {orig_expected_path}")
198+
f"following file cannot be accessed: "
199+
f"{orig_expected_path}") from err
199200
return expected_fname
200201

201202
def compare(self, idx, baseline, extension):

lib/matplotlib/text.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,15 +53,15 @@ def get_rotation(rotation):
5353
"""
5454
try:
5555
return float(rotation) % 360
56-
except (ValueError, TypeError):
56+
except (ValueError, TypeError) as err:
5757
if cbook._str_equal(rotation, 'horizontal') or rotation is None:
5858
return 0.
5959
elif cbook._str_equal(rotation, 'vertical'):
6060
return 90.
6161
else:
6262
raise ValueError("rotation is {!r}; expected either 'horizontal', "
6363
"'vertical', numeric value, or None"
64-
.format(rotation))
64+
.format(rotation)) from err
6565

6666

6767
def _get_textbox(text, renderer):

lib/matplotlib/ticker.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2849,8 +2849,9 @@ def get_locator(self, d):
28492849

28502850
try:
28512851
ld = math.log10(d)
2852-
except OverflowError:
2853-
raise RuntimeError('AutoLocator illegal data interval range')
2852+
except OverflowError as err:
2853+
raise RuntimeError('AutoLocator illegal data interval '
2854+
'range') from err
28542855

28552856
fld = math.floor(ld)
28562857
base = 10 ** fld

lib/matplotlib/tri/triinterpolate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,9 +191,9 @@ def _interpolate_multikeys(self, x, y, tri_index=None,
191191
# Find the return index associated with the key.
192192
try:
193193
return_index = {'z': 0, 'dzdx': 1, 'dzdy': 2}[return_key]
194-
except KeyError:
194+
except KeyError as err:
195195
raise ValueError("return_keys items shall take values in"
196-
" {'z', 'dzdx', 'dzdy'}")
196+
" {'z', 'dzdx', 'dzdy'}") from err
197197

198198
# Sets the scale factor for f & df components
199199
scale = [1., 1./self._unit_x, 1./self._unit_y][return_index]

lib/mpl_toolkits/axes_grid1/axes_rgb.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,12 +114,12 @@ def __init__(self, *args, pad=0, add_all=True, **kwargs):
114114
"""
115115
try:
116116
axes_class = kwargs.pop("axes_class", self._defaultAxesClass)
117-
except AttributeError:
117+
except AttributeError as err:
118118
raise AttributeError(
119119
'A subclass of RGBAxesBase must have a _defaultAxesClass '
120120
'attribute. If you are not sure which axes class to use, '
121121
'consider using mpl_toolkits.axes_grid1.mpl_axes.Axes.'
122-
)
122+
) from err
123123

124124
ax = axes_class(*args, **kwargs)
125125

tools/boilerplate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,9 +343,9 @@ def build_pyplot():
343343
pyplot_orig = pyplot_path.read_text().splitlines(keepends=True)
344344
try:
345345
pyplot_orig = pyplot_orig[:pyplot_orig.index(PYPLOT_MAGIC_HEADER) + 1]
346-
except IndexError:
346+
except IndexError as err:
347347
raise ValueError('The pyplot.py file *must* have the exact line: %s'
348-
% PYPLOT_MAGIC_HEADER)
348+
% PYPLOT_MAGIC_HEADER) from err
349349

350350
with pyplot_path.open('w') as pyplot:
351351
pyplot.writelines(pyplot_orig)

tools/gh_api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ class Obj(dict):
2424
def __getattr__(self, name):
2525
try:
2626
return self[name]
27-
except KeyError:
28-
raise AttributeError(name)
27+
except KeyError as err:
28+
raise AttributeError(name) from err
2929

3030
def __setattr__(self, name, val):
3131
self[name] = val

tools/memleak.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
try:
88
import psutil
9-
except ImportError:
10-
raise ImportError("This script requires psutil")
9+
except ImportError as err:
10+
raise ImportError("This script requires psutil") from err
1111

1212
import numpy as np
1313

0 commit comments

Comments
 (0)
0