From c89ac3eaec7f05936819a9350464ece643cbe4c3 Mon Sep 17 00:00:00 2001 From: Ram Rachum Date: Thu, 5 Mar 2020 19:41:01 +0200 Subject: [PATCH] Fix exception causes in 19 modules --- lib/matplotlib/markers.py | 4 ++-- lib/matplotlib/mathtext.py | 11 ++++++----- lib/matplotlib/offsetbox.py | 5 +++-- lib/matplotlib/patches.py | 9 +++++---- lib/matplotlib/projections/__init__.py | 4 ++-- lib/matplotlib/pyplot.py | 4 ++-- lib/matplotlib/sphinxext/plot_directive.py | 12 ++++++------ lib/matplotlib/streamplot.py | 5 +++-- lib/matplotlib/style/core.py | 4 ++-- lib/matplotlib/table.py | 5 +++-- lib/matplotlib/testing/compare.py | 13 +++++++------ lib/matplotlib/testing/decorators.py | 5 +++-- lib/matplotlib/text.py | 4 ++-- lib/matplotlib/ticker.py | 5 +++-- lib/matplotlib/tri/triinterpolate.py | 4 ++-- lib/mpl_toolkits/axes_grid1/axes_rgb.py | 4 ++-- tools/boilerplate.py | 4 ++-- tools/gh_api.py | 4 ++-- tools/memleak.py | 4 ++-- 19 files changed, 59 insertions(+), 51 deletions(-) diff --git a/lib/matplotlib/markers.py b/lib/matplotlib/markers.py index bab0d4a600b8..c9d7a167a1ba 100644 --- a/lib/matplotlib/markers.py +++ b/lib/matplotlib/markers.py @@ -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() diff --git a/lib/matplotlib/mathtext.py b/lib/matplotlib/mathtext.py index dc8ff1c0a906..9f6c076d2998 100644 --- a/lib/matplotlib/mathtext.py +++ b/lib/matplotlib/mathtext.py @@ -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: @@ -2582,7 +2582,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() @@ -2697,8 +2697,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 diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py index a3693c9cd219..56010a3975f0 100644 --- a/lib/matplotlib/offsetbox.py +++ b/lib/matplotlib/offsetbox.py @@ -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] diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index d7dcda251310..ee2c29e85a54 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -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) diff --git a/lib/matplotlib/projections/__init__.py b/lib/matplotlib/projections/__init__.py index 8f854b47d744..556273803665 100644 --- a/lib/matplotlib/projections/__init__.py +++ b/lib/matplotlib/projections/__init__.py @@ -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 diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index b5a2c3cd6c95..f52f511c648b 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -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: diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index d88425ac6ebc..d4c96f5d06e8 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -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) @@ -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 @@ -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)) diff --git a/lib/matplotlib/streamplot.py b/lib/matplotlib/streamplot.py index e5783d95e46f..0477ec00c227 100644 --- a/lib/matplotlib/streamplot.py +++ b/lib/matplotlib/streamplot.py @@ -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)) diff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py index 2ea1092b57cf..809ba212af9f 100644 --- a/lib/matplotlib/style/core.py +++ b/lib/matplotlib/style/core.py @@ -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 diff --git a/lib/matplotlib/table.py b/lib/matplotlib/table.py index 4bea75f6f2ee..f0c8c9c00eaa 100644 --- a/lib/matplotlib/table.py +++ b/lib/matplotlib/table.py @@ -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) diff --git a/lib/matplotlib/testing/compare.py b/lib/matplotlib/testing/compare.py index 8e2bec4a7bd6..41d1c47cb998 100644 --- a/lib/matplotlib/testing/compare.py +++ b/lib/matplotlib/testing/compare.py @@ -135,8 +135,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) @@ -189,8 +189,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`. @@ -207,14 +208,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(): diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 65d030ed9afe..6fa8a1a62973 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -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): diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index 78fb5c57f7e2..f67afa763d1d 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -53,7 +53,7 @@ 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'): @@ -61,7 +61,7 @@ def get_rotation(rotation): 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): diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index 8cffd92046c7..63f5a0676405 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -2848,8 +2848,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 diff --git a/lib/matplotlib/tri/triinterpolate.py b/lib/matplotlib/tri/triinterpolate.py index 309b0cc60fef..58b62f949aac 100644 --- a/lib/matplotlib/tri/triinterpolate.py +++ b/lib/matplotlib/tri/triinterpolate.py @@ -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] diff --git a/lib/mpl_toolkits/axes_grid1/axes_rgb.py b/lib/mpl_toolkits/axes_grid1/axes_rgb.py index 936af23d9928..215748d649c7 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_rgb.py +++ b/lib/mpl_toolkits/axes_grid1/axes_rgb.py @@ -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) diff --git a/tools/boilerplate.py b/tools/boilerplate.py index 780044e801ee..58d4fb3c17fd 100644 --- a/tools/boilerplate.py +++ b/tools/boilerplate.py @@ -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) diff --git a/tools/gh_api.py b/tools/gh_api.py index e02648e6bb10..71879264a4ac 100644 --- a/tools/gh_api.py +++ b/tools/gh_api.py @@ -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 diff --git a/tools/memleak.py b/tools/memleak.py index 41a4d63b194a..97bb8adae386 100755 --- a/tools/memleak.py +++ b/tools/memleak.py @@ -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