8000 Fix exception causes all over the codebase by cool-RR · Pull Request #16706 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Fix exception causes all over the codebase #16706

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions doc/sphinxext/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions examples/user_interfaces/embedding_webagg_sgskip.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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():
Expand Down
10 changes: 5 additions & 5 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
13 changes: 7 additions & 6 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()},
Expand All @@ -2904,9 +2905,9 @@ def ticklabel_format(self, *, axis='both', style='', scilimits=None,
axis.major.formatter.set_useLocale( 9E88 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):
"""
Expand Down
11 changes: 6 additions & 5 deletions lib/matplotlib/backends/backend_agg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`."""
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_cairo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/backends/backend_gtk3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/backends/backend_nbagg.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,10 @@ def __init__(self, manager):
display(HTML("<div id=%r></div>" % 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
Expand Down
17 changes: 9 additions & 8 deletions lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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}")
Expand All @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_webagg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/backends/qt_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
12 changes: 6 additions & 6 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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'):
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/font_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/fontconfig_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
0