diff --git a/doc/sphinxext/github.py b/doc/sphinxext/github.py index f98c3c89e05d..be4017e24ed4 100644 --- a/doc/sphinxext/github.py +++ b/doc/sphinxext/github.py @@ -39,7 +39,8 @@ def make_link_node(rawtext, app, type, slug, options): base += '/' except AttributeError as err: raise ValueError( - f'github_project_url configuration value is not set ({err})') + f'github_project_url configuration value is not set ' + f'({err})') from err ref = base + type + '/' + slug + '/' set_classes(options) @@ -137,7 +138,8 @@ def ghcommit_role( base += '/' except AttributeError as err: raise ValueError( - f'github_project_url configuration value is not set ({err})') + f'github_project_url configuration value is not set ' + f'({err})') from err ref = base + text node = nodes.reference(rawtext, text[:6], refuri=ref, **options) diff --git a/examples/user_interfaces/embedding_webagg_sgskip.py b/examples/user_interfaces/embedding_webagg_sgskip.py index 383acf0c39f6..7984c0f557d9 100644 --- a/examples/user_interfaces/embedding_webagg_sgskip.py +++ b/examples/user_interfaces/embedding_webagg_sgskip.py @@ -16,8 +16,8 @@ try: import tornado -except ImportError: - raise RuntimeError("This example requires tornado.") +except ImportError as err: + raise RuntimeError("This example requires tornado.") from err import tornado.web import tornado.httpserver import tornado.ioloop diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 6b02229bcd42..7eb23fc22d72 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -656,10 +656,10 @@ def __setitem__(self, key, val): except ValueError as ve: raise ValueError(f"Key {key}: {ve}") from None dict.__setitem__(self, key, cval) - except KeyError: + except KeyError as err: raise KeyError( f"{key} is not a valid rc parameter (see rcParams.keys() for " - f"a list of valid parameters)") + f"a list of valid parameters)") from err def __getitem__(self, key): if key in _deprecated_map: @@ -942,9 +942,9 @@ def rc(group, **kwargs): key = '%s.%s' % (g, name) try: rcParams[key] = v - except KeyError: + except KeyError as err: raise KeyError(('Unrecognized key "%s" for group "%s" and ' - 'name "%s"') % (key, g, name)) + 'name "%s"') % (key, g, name)) from err def rcdefaults(): diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index b20417af3046..d379e08fda10 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -4210,11 +4210,11 @@ def _parse_scatter_color_args(c, edgecolors, kwargs, xsize, if kwcolor is not None: try: mcolors.to_rgba_array(kwcolor) - except ValueError: + except ValueError as err: raise ValueError( "'color' kwarg must be an color or sequence of color " "specs. For a sequence of values to be color-mapped, use " - "the 'c' argument instead.") + "the 'c' argument instead.") from err if edgecolors is None: edgecolors = kwcolor if facecolors is None: @@ -4264,14 +4264,14 @@ def invalid_shape_exception(csize, xsize): if not c_is_mapped: try: # Is 'c' acceptable as PathCollection facecolors? colors = mcolors.to_rgba_array(c) - except (TypeError, ValueError): + except (TypeError, ValueError) as err: if not valid_shape: - raise invalid_shape_exception(c.size, xsize) + raise invalid_shape_exception(c.size, xsize) from err # Both the mapping *and* the RGBA conversion failed: pretty # severe failure => one may appreciate a verbose feedback. raise ValueError( f"'c' argument must be a color, a sequence of colors, or " - f"a sequence of numbers, not {c}") + f"a sequence of numbers, not {c}") from err else: if len(colors) not in (0, 1, xsize): # NB: remember that a single color is also acceptable. diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index db47c347b9bf..6383fb3161ba 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -1732,10 +1732,10 @@ def axis(self, *args, emit=True, **kwargs): limits = args[0] try: xmin, xmax, ymin, ymax = limits - except (TypeError, ValueError): + except (TypeError, ValueError) as err: raise TypeError('the first argument to axis() must be an ' 'interable of the form ' - '[xmin, xmax, ymin, ymax]') + '[xmin, xmax, ymin, ymax]') from err else: xmin = kwargs.pop('xmin', None) xmax = kwargs.pop('xmax', None) @@ -2885,8 +2885,9 @@ def ticklabel_format(self, *, axis='both', style='', scilimits=None, try: m, n = scilimits m + n + 1 # check that both are numbers - except (ValueError, TypeError): - raise ValueError("scilimits must be a sequence of 2 integers") + except (ValueError, TypeError) as err: + raise ValueError("scilimits must be a sequence of 2 integers" + ) from err STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None} is_sci_style = cbook._check_getitem(STYLES, style=style) axis_map = {**{k: [v] for k, v in self._get_axis_map().items()}, @@ -2904,9 +2905,9 @@ def ticklabel_format(self, *, axis='both', style='', scilimits=None, axis.major.formatter.set_useLocale(useLocale) if useMathText is not None: axis.major.formatter.set_useMathText(useMathText) - except AttributeError: + except AttributeError as err: raise AttributeError( - "This method only works with the ScalarFormatter") + "This method only works with the ScalarFormatter") from err def locator_params(self, axis='both', tight=None, **kwargs): """ diff --git a/lib/matplotlib/backends/backend_agg.py b/lib/matplotlib/backends/backend_agg.py index b6cae5b80732..c4cc22d24a3e 100644 --- a/lib/matplotlib/backends/backend_agg.py +++ b/lib/matplotlib/backends/backend_agg.py @@ -143,15 +143,16 @@ def draw_path(self, gc, path, transform, rgbFace=None): p = Path(v, c) try: self._renderer.draw_path(gc, p, transform, rgbFace) - except OverflowError: - raise OverflowError("Exceeded cell block limit (set " - "'agg.path.chunksize' rcparam)") + except OverflowError as err: + raise OverflowError( + "Exceeded cell block limit (set 'agg.path.chunksize' " + "rcparam)") from err else: try: self._renderer.draw_path(gc, path, transform, rgbFace) - except OverflowError: + except OverflowError as err: raise OverflowError("Exceeded cell block limit (set " - "'agg.path.chunksize' rcparam)") + "'agg.path.chunksize' rcparam)") from err def draw_mathtext(self, gc, x, y, s, prop, angle): """Draw mathtext using :mod:`matplotlib.mathtext`.""" diff --git a/lib/matplotlib/backends/backend_cairo.py b/lib/matplotlib/backends/backend_cairo.py index 4b1d7a8b11ce..ba4c75df2fb9 100644 --- a/lib/matplotlib/backends/backend_cairo.py +++ b/lib/matplotlib/backends/backend_cairo.py @@ -18,10 +18,10 @@ except ImportError: try: import cairocffi as cairo - except ImportError: + except ImportError as err: raise ImportError( "cairo backend requires that pycairo>=1.11.0 or cairocffi" - "is installed") + "is installed") from err from .. import cbook from matplotlib.backend_bases import ( diff --git a/lib/matplotlib/backends/backend_gtk3.py b/lib/matplotlib/backends/backend_gtk3.py index 8cbe35e8001d..0e8dc97a48d8 100644 --- a/lib/matplotlib/backends/backend_gtk3.py +++ b/lib/matplotlib/backends/backend_gtk3.py @@ -16,8 +16,8 @@ try: import gi -except ImportError: - raise ImportError("The GTK3 backends require PyGObject") +except ImportError as err: + raise ImportError("The GTK3 backends require PyGObject") from err try: # :raises ValueError: If module/version is already loaded, already @@ -47,7 +47,7 @@ except TypeError as exc: # Happens when running headless. Convert to ImportError to cooperate with # backend switching. - raise ImportError(exc) + raise ImportError(exc) from exc class TimerGTK3(TimerBase): diff --git a/lib/matplotlib/backends/backend_nbagg.py b/lib/matplotlib/backends/backend_nbagg.py index 8a77b451a157..c61d2a13d86b 100644 --- a/lib/matplotlib/backends/backend_nbagg.py +++ b/lib/matplotlib/backends/backend_nbagg.py @@ -164,9 +164,10 @@ def __init__(self, manager): display(HTML("
" % self.uuid)) try: self.comm = Comm('matplotlib', data={'id': self.uuid}) - except AttributeError: + except AttributeError as err: raise RuntimeError('Unable to create an IPython notebook Comm ' - 'instance. Are you in the IPython notebook?') + 'instance. Are you in the IPython ' + 'notebook?') from err self.comm.on_msg(self.on_message) manager = self.manager diff --git a/lib/matplotlib/backends/backend_pgf.py b/lib/matplotlib/backends/backend_pgf.py index 4c38522277cc..da124a2dde69 100644 --- a/lib/matplotlib/backends/backend_pgf.py +++ b/lib/matplotlib/backends/backend_pgf.py @@ -273,13 +273,14 @@ def __init__(self): [self.texcommand, "-halt-on-error"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding="utf-8", cwd=self.tmpdir) - except FileNotFoundError: + except FileNotFoundError as err: raise RuntimeError( f"{self.texcommand} not found. Install it or change " f"rcParams['pgf.texsystem'] to an available TeX " - f"implementation.") - except OSError: - raise RuntimeError("Error starting process %r" % self.texcommand) + f"implementation.") from err + except OSError as err: + raise RuntimeError("Error starting process %r" % + self.texcommand) from err test_input = self.latex_header + latex_end stdout, stderr = latex.communicate(test_input) if latex.returncode != 0: @@ -342,7 +343,7 @@ def get_width_height_descent(self, text, prop): self._expect_prompt() except LatexError as e: raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" - .format(text, e.latex_output)) + .format(text, e.latex_output)) from e # typeout width, height and text offset of the last textbox self._stdin_writeln(r"\typeout{\the\wd0,\the\ht0,\the\dp0}") @@ -351,14 +352,14 @@ def get_width_height_descent(self, text, prop): answer = self._expect_prompt() except LatexError as e: raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" - .format(text, e.latex_output)) + .format(text, e.latex_output)) from e # parse metrics from the answer string try: width, height, offset = answer.splitlines()[0].split(",") - except Exception: + except Exception as err: raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" - .format(text, answer)) + .format(text, answer)) from err w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2]) # the height returned from LaTeX goes from base to top. diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index e1ef94010c06..730cd5e11f98 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1023,9 +1023,9 @@ def _print_figure_tex( else: try: title = os.fspath(outfile) - except TypeError: + except TypeError as err: raise ValueError( - "outfile must be a path or a file-like object") + "outfile must be a path or a file-like object") from err self.figure.dpi = 72 # ignore the dpi kwarg width, height = self.figure.get_size_inches() diff --git a/lib/matplotlib/backends/backend_webagg.py b/lib/matplotlib/backends/backend_webagg.py index 545d7ff9098e..cd5ada8cd073 100644 --- a/lib/matplotlib/backends/backend_webagg.py +++ b/lib/matplotlib/backends/backend_webagg.py @@ -25,8 +25,8 @@ try: import tornado -except ImportError: - raise RuntimeError("The WebAgg backend requires Tornado.") +except ImportError as err: + raise RuntimeError("The WebAgg backend requires Tornado.") from err import tornado.web import tornado.ioloop diff --git a/lib/matplotlib/backends/qt_compat.py b/lib/matplotlib/backends/qt_compat.py index 6b52284fe7f4..2ec7ff4df0c1 100644 --- a/lib/matplotlib/backends/qt_compat.py +++ b/lib/matplotlib/backends/qt_compat.py @@ -56,10 +56,11 @@ else: try: QT_API = _ETS[QT_API_ENV] - except KeyError: + except KeyError as err: raise RuntimeError( "The environment variable QT_API has the unrecognized value {!r};" - "valid values are 'pyqt5', 'pyside2', 'pyqt', and 'pyside'") + "valid values are 'pyqt5', 'pyside2', 'pyqt', and " + "'pyside'") from err def _setup_pyqt5(): diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 5c9a419ed353..4d663f1c0293 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -721,11 +721,11 @@ def report_memory(i=0): # argument may go away def call(command, os_name): try: return subprocess.check_output(command) - except subprocess.CalledProcessError: + except subprocess.CalledProcessError as err: raise NotImplementedError( "report_memory works on %s only if " "the '%s' program is found" % (os_name, command[0]) - ) + ) from err pid = os.getpid() if sys.platform == 'sunos5': diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 12ab6a583790..415f3c110797 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -100,8 +100,9 @@ def register_cmap(name=None, cmap=None, data=None, lut=None): if name is None: try: name = cmap.name - except AttributeError: - raise ValueError("Arguments must include a name or a Colormap") + except AttributeError as err: + raise ValueError("Arguments must include a name or a " + "Colormap") from err if isinstance(cmap, colors.Colormap): cmap_d[name] = cmap return diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index 74b99bf98ebc..94b1ce1ed91b 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -581,9 +581,9 @@ def set_linestyle(self, ls): except ValueError: dashes = [mlines._get_dash_pattern(x) for x in ls] - except ValueError: - raise ValueError( - 'Do not know how to convert {!r} to dashes'.format(ls)) + except ValueError as err: + raise ValueError('Do not know how to convert {!r} to ' + 'dashes'.format(ls)) from err # get the list of raw 'unscaled' dash patterns self._us_linestyles = dashes diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index f95e0f952b3d..5cf5d13cd9e7 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -1038,9 +1038,9 @@ def _get_extension_lengths(self, frac, automin, automax, default=0.05): # be encountered. This is an error. if np.isnan(extendlength).any(): raise ValueError() - except (TypeError, ValueError): + except (TypeError, ValueError) as err: # Raise an error on encountering an invalid value for frac. - raise ValueError('invalid value for extendfrac') + raise ValueError('invalid value for extendfrac') from err return extendlength def _uniform_y(self, N): diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index fb779a29cd82..967cfe101ce6 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -315,11 +315,11 @@ def to_rgba_array(c, alpha=None): # This is deprecated and will be removed in the future. try: result = np.array([to_rgba(cc, alpha) for cc in c]) - except ValueError: + except ValueError as err: raise ValueError( "'%s' is neither a valid single color nor a color sequence " "consisting of single character color specifiers such as " - "'rgb'. Note also that the latter is deprecated." % c) + "'rgb'. Note also that the latter is deprecated." % c) from err else: cbook.warn_deprecated("3.2", message="Using a string of single " "character colors as a color sequence is " @@ -443,8 +443,8 @@ def _create_lookup_table(N, data, gamma=1.0): try: adata = np.array(data) - except Exception: - raise TypeError("data must be convertible to an array") + except Exception as err: + raise TypeError("data must be convertible to an array") from err shape = adata.shape if len(shape) != 2 or shape[1] != 3: raise ValueError("data must be nx3 format") @@ -1894,9 +1894,9 @@ def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv', else: try: blend = blend_mode(rgb, intensity, **kwargs) - except TypeError: + except TypeError as err: raise ValueError('"blend_mode" must be callable or one of {}' - .format(lookup.keys)) + .format(lookup.keys)) from err # Only apply result where hillshade intensity isn't masked if hasattr(intensity, 'mask'): diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index 311257ad84c9..66e6b4597bae 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -806,9 +806,9 @@ def set_stretch(self, stretch): stretch = int(stretch) if stretch < 0 or stretch > 1000: raise ValueError() - except ValueError: + except ValueError as err: if stretch not in stretch_dict: - raise ValueError("stretch is invalid") + raise ValueError("stretch is invalid") from err self._stretch = stretch def set_size(self, size): @@ -824,10 +824,10 @@ def set_size(self, size): except ValueError: try: scale = font_scalings[size] - except KeyError: + except KeyError as err: raise ValueError( "Size is invalid. Valid font size are " - + ", ".join(map(str, font_scalings))) + + ", ".join(map(str, font_scalings))) from err else: size = scale * FontManager.get_default_size() if size < 1.0: diff --git a/lib/matplotlib/fontconfig_pattern.py b/lib/matplotlib/fontconfig_pattern.py index e56df0bed4fe..c47e19bf99dc 100644 --- a/lib/matplotlib/fontconfig_pattern.py +++ b/lib/matplotlib/fontconfig_pattern.py @@ -127,7 +127,7 @@ def parse(self, pattern): self._parser.parseString(pattern) except self.ParseException as e: raise ValueError( - "Could not parse font string: '%s'\n%s" % (pattern, e)) + "Could not parse font string: '%s'\n%s" % (pattern, e)) from e self._properties = None diff --git a/lib/matplotlib/gridspec.py b/lib/matplotlib/gridspec.py index b8090c0293ee..c6ecd6a5c99b 100644 --- a/lib/matplotlib/gridspec.py +++ b/lib/matplotlib/gridspec.py @@ -224,8 +224,8 @@ def _normalize(key, size, axis): # Includes last index. if isinstance(key, tuple): try: k1, k2 = key - except ValueError: - raise ValueError("Unrecognized subplot spec") + except ValueError as err: + raise ValueError("Unrecognized subplot spec") from err num1, num2 = np.ravel_multi_index( [_normalize(k1, nrows, 0), _normalize(k2, ncols, 1)], (nrows, ncols)) @@ -543,9 +543,9 @@ def _from_subplot_args(figure, args): try: s = str(int(arg)) rows, cols, num = map(int, s) - except ValueError: + except ValueError as err: raise ValueError("Single argument to subplot must be a " - "3-digit integer") + "3-digit integer") from err # num - 1 for converting from MATLAB to python indexing return GridSpec(rows, cols, figure=figure)[num - 1] elif len(args) == 3: diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 74a308804214..3dc589ca1618 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -1587,8 +1587,8 @@ def pil_to_array(pilImage): else: # try to convert to an rgba image try: pilImage = pilImage.convert('RGBA') - except ValueError: - raise RuntimeError('Unknown image mode') + except ValueError as err: + raise RuntimeError('Unknown image mode') from err return np.asarray(pilImage) # return MxNx4 RGBA array diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 9da20b65c489..8e76cc9a6c73 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -950,8 +950,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/lines.py b/lib/matplotlib/lines.py index 76c256dfa185..fd6f103a2c0d 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -188,10 +188,10 @@ def _slice_or_none(in_v, slc): # fancy indexing try: return Path(verts[markevery], _slice_or_none(codes, markevery)) - except (ValueError, IndexError): + except (ValueError, IndexError) as err: raise ValueError( f"markevery={markevery!r} is iterable but not a valid numpy " - f"fancy index") + f"fancy index") from err else: raise ValueError(f"markevery={markevery!r} is not a recognized value")