Skip to content

Commit

Permalink
Merge pull request matplotlib#16684 from cool-RR/2020-03-05-raise-from
Browse files Browse the repository at this point in the history
Fix exception causes in 19 modules
  • Loading branch information
anntzer authored Mar 6, 2020
2 parents 4595bbd + c89ac3e commit 376b75d
Show file tree
Hide file tree
Showing 19 changed files with 59 additions and 51 deletions.
4 changes: 2 additions & 2 deletions lib/matplotlib/markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,9 +287,9 @@ def set_marker(self, marker):
try:
Path(marker)
self._marker_function = self._set_vertices
except ValueError:
except ValueError as err:
raise ValueError('Unrecognized marker style {!r}'
.format(marker))
.format(marker)) from err

self._marker = marker
self._recache()
Expand Down
11 changes: 6 additions & 5 deletions lib/matplotlib/mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ def get_unicode_index(symbol, math=True):
pass
try: # Is symbol a TeX symbol (i.e. \alpha)
return tex2uni[symbol.strip("\\")]
except KeyError:
except KeyError as err:
raise ValueError(
"'{}' is not a valid Unicode character or TeX/Type1 symbol"
.format(symbol))
.format(symbol)) from err


class MathtextBackend:
Expand Down Expand Up @@ -2616,7 +2616,7 @@ def parse(self, s, fonts_object, fontsize, dpi):
raise ValueError("\n".join(["",
err.line,
" " * (err.column - 1) + "^",
str(err)]))
str(err)])) from err
self._state_stack = None
self._em_width_cache = {}
self._expression.resetCache()
Expand Down Expand Up @@ -2731,8 +2731,9 @@ def symbol(self, s, loc, toks):
c = toks[0]
try:
char = Char(c, self.get_state())
except ValueError:
raise ParseFatalException(s, loc, "Unknown symbol: %s" % c)
except ValueError as err:
raise ParseFatalException(s, loc,
"Unknown symbol: %s" % c) from err

if c in self._spaced_symbols:
# iterate until we find previous character, needed for cases
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/offsetbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -1167,8 +1167,9 @@ def set_bbox_to_anchor(self, bbox, transform=None):
else:
try:
l = len(bbox)
except TypeError:
raise ValueError("Invalid argument for bbox : %s" % str(bbox))
except TypeError as err:
raise ValueError("Invalid argument for bbox : %s" %
str(bbox)) from err

if l == 2:
bbox = [bbox[0], bbox[1], 0, 0]
Expand Down
9 changes: 5 additions & 4 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -1844,14 +1844,15 @@ def __new__(cls, stylename, **kw):
_name = _list[0].lower()
try:
_cls = cls._style_list[_name]
except KeyError:
raise ValueError("Unknown style : %s" % stylename)
except KeyError as err:
raise ValueError("Unknown style : %s" % stylename) from err

try:
_args_pair = [cs.split("=") for cs in _list[1:]]
_args = {k: float(v) for k, v in _args_pair}
except ValueError:
raise ValueError("Incorrect style argument : %s" % stylename)
except ValueError as err:
raise ValueError("Incorrect style argument : %s" %
stylename) from err
_args.update(kw)

return _cls(**_args)
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/projections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ def get_projection_class(projection=None):

try:
return projection_registry.get_projection_class(projection)
except KeyError:
raise ValueError("Unknown projection %r" % projection)
except KeyError as err:
raise ValueError("Unknown projection %r" % projection) from err


get_projection_names = projection_registry.get_projection_names
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,9 @@ def uninstall_repl_displayhook():
ip = get_ipython()
try:
ip.events.unregister('post_execute', _IP_REGISTERED)
except AttributeError:
except AttributeError as err:
raise NotImplementedError("Can not unregister events "
"in IPython < 2.0")
"in IPython < 2.0") from err
_IP_REGISTERED = None

if _INSTALL_FIG_OBSERVER:
Expand Down
12 changes: 6 additions & 6 deletions lib/matplotlib/sphinxext/plot_directive.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,11 +444,11 @@ def run_code(code, code_path, ns=None, function_name=None):
except OSError as err:
raise OSError(str(err) + '\n`plot_working_directory` option in'
'Sphinx configuration file must be a valid '
'directory path')
'directory path') from err
except TypeError as err:
raise TypeError(str(err) + '\n`plot_working_directory` option in '
'Sphinx configuration file must be a string or '
'None')
'None') from err
elif code_path is not None:
dirname = os.path.abspath(os.path.dirname(code_path))
os.chdir(dirname)
Expand All @@ -475,8 +475,8 @@ def run_code(code, code_path, ns=None, function_name=None):
if function_name is not None:
exec(function_name + "()", ns)

except (Exception, SystemExit):
raise PlotError(traceback.format_exc())
except (Exception, SystemExit) as err:
raise PlotError(traceback.format_exc()) from err
finally:
os.chdir(pwd)
return ns
Expand Down Expand Up @@ -600,8 +600,8 @@ def render_figures(code, code_path, output_dir, output_base, context,
for fmt, dpi in formats:
try:
figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi)
except Exception:
raise PlotError(traceback.format_exc())
except Exception as err:
raise PlotError(traceback.format_exc()) from err
img.formats.append(fmt)

results.append((code_piece, images))
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/streamplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,8 +372,9 @@ class StreamMask:
def __init__(self, density):
try:
self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int)
except ValueError:
raise ValueError("'density' must be a scalar or be of length 2")
except ValueError as err:
raise ValueError("'density' must be a scalar or be of length "
"2") from err
if self.nx < 0 or self.ny < 0:
raise ValueError("'density' must be positive")
self._mask = np.zeros((self.ny, self.nx))
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/style/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ def use(style):
try:
rc = rc_params_from_file(style, use_default_template=False)
_apply_style(rc)
except IOError:
except IOError as err:
raise IOError(
"{!r} not found in the style library and input is not a "
"valid URL or path; see `style.available` for list of "
"available styles".format(style))
"available styles".format(style)) from err


@contextlib.contextmanager
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,8 +358,9 @@ def __setitem__(self, position, cell):
cbook._check_isinstance(CustomCell, cell=cell)
try:
row, col = position[0], position[1]
except Exception:
raise KeyError('Only tuples length 2 are accepted as coordinates')
except Exception as err:
raise KeyError('Only tuples length 2 are accepted as '
'coordinates') from err
cell.set_figure(self.figure)
cell.set_transform(self.get_transform())
cell.set_clip_on(False)
Expand Down
13 changes: 7 additions & 6 deletions lib/matplotlib/testing/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ def __call__(self, orig, dest):
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
try:
self._read_until(b"\nGS")
except _ConverterError:
raise OSError("Failed to start Ghostscript")
except _ConverterError as err:
raise OSError("Failed to start Ghostscript") from err

def encode_and_escape(name):
return (os.fsencode(name)
Expand Down Expand Up @@ -181,8 +181,9 @@ def __call__(self, orig, dest):
self._proc.stderr = stderr
try:
self._read_until(b"\n>")
except _ConverterError:
raise OSError("Failed to start Inkscape in interactive mode")
except _ConverterError as err:
raise OSError("Failed to start Inkscape in interactive "
"mode") from err

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


def _update_converter():
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/testing/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,11 @@ def copy_baseline(self, baseline, extension):
os.symlink(orig_expected_path, expected_fname)
except OSError: # On Windows, symlink *may* be unavailable.
shutil.copyfile(orig_expected_path, expected_fname)
except OSError:
except OSError as err:
raise ImageComparisonFailure(
f"Missing baseline image {expected_fname} because the "
f"following file cannot be accessed: {orig_expected_path}")
f"following file cannot be accessed: "
f"{orig_expected_path}") from err
return expected_fname

def compare(self, idx, baseline, extension):
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ def get_rotation(rotation):
"""
try:
return float(rotation) % 360
except (ValueError, TypeError):
except (ValueError, TypeError) as err:
if cbook._str_equal(rotation, 'horizontal') or rotation is None:
return 0.
elif cbook._str_equal(rotation, 'vertical'):
return 90.
else:
raise ValueError("rotation is {!r}; expected either 'horizontal', "
"'vertical', numeric value, or None"
.format(rotation))
.format(rotation)) from err


def _get_textbox(text, renderer):
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2849,8 +2849,9 @@ def get_locator(self, d):

try:
ld = math.log10(d)
except OverflowError:
raise RuntimeError('AutoLocator illegal data interval range')
except OverflowError as err:
raise RuntimeError('AutoLocator illegal data interval '
'range') from err

fld = math.floor(ld)
base = 10 ** fld
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tri/triinterpolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,9 @@ def _interpolate_multikeys(self, x, y, tri_index=None,
# Find the return index associated with the key.
try:
return_index = {'z': 0, 'dzdx': 1, 'dzdy': 2}[return_key]
except KeyError:
except KeyError as err:
raise ValueError("return_keys items shall take values in"
" {'z', 'dzdx', 'dzdy'}")
" {'z', 'dzdx', 'dzdy'}") from err

# Sets the scale factor for f & df components
scale = [1., 1./self._unit_x, 1./self._unit_y][return_index]
Expand Down
4 changes: 2 additions & 2 deletions lib/mpl_toolkits/axes_grid1/axes_rgb.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,12 @@ def __init__(self, *args, pad=0, add_all=True, **kwargs):
"""
try:
axes_class = kwargs.pop("axes_class", self._defaultAxesClass)
except AttributeError:
except AttributeError as err:
raise AttributeError(
'A subclass of RGBAxesBase must have a _defaultAxesClass '
'attribute. If you are not sure which axes class to use, '
'consider using mpl_toolkits.axes_grid1.mpl_axes.Axes.'
)
) from err

ax = axes_class(*args, **kwargs)

Expand Down
4 changes: 2 additions & 2 deletions tools/boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,9 +343,9 @@ def build_pyplot():
pyplot_orig = pyplot_path.read_text().splitlines(keepends=True)
try:
pyplot_orig = pyplot_orig[:pyplot_orig.index(PYPLOT_MAGIC_HEADER) + 1]
except IndexError:
except IndexError as err:
raise ValueError('The pyplot.py file *must* have the exact line: %s'
% PYPLOT_MAGIC_HEADER)
% PYPLOT_MAGIC_HEADER) from err

with pyplot_path.open('w') as pyplot:
pyplot.writelines(pyplot_orig)
Expand Down
4 changes: 2 additions & 2 deletions tools/gh_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ class Obj(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
except KeyError as err:
raise AttributeError(name) from err

def __setattr__(self, name, val):
self[name] = val
Expand Down
4 changes: 2 additions & 2 deletions tools/memleak.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

try:
import psutil
except ImportError:
raise ImportError("This script requires psutil")
except ImportError as err:
raise ImportError("This script requires psutil") from err

import numpy as np

Expand Down

0 comments on commit 376b75d

Please sign in to comment.