Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 40d7449

Browse files
committed
Fix exception causes all over the codebase
1 parent fe34774 commit 40d7449

24 files changed

+84
-75
lines changed

doc/sphinxext/github.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ def make_link_node(rawtext, app, type, slug, options):
3939
base += '/'
4040
except AttributeError as err:
4141
raise ValueError(
42-
f'github_project_url configuration value is not set ({err})')
42+
f'github_project_url configuration value is not set '
43+
f'({err})') from err
4344

4445
ref = base + type + '/' + slug + '/'
4546
set_classes(options)
@@ -137,7 +138,8 @@ def ghcommit_role(
137138
base += '/'
138139
except AttributeError as err:
139140
raise ValueError(
140-
f'github_project_url configuration value is not set ({err})')
141+
f'github_project_url configuration value is not set '
142+
f'({err})') from err
141143

142144
ref = base + text
143145
node = nodes.reference(rawtext, text[:6], refuri=ref, **options)

examples/user_interfaces/embedding_webagg_sgskip.py

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

1717
try:
1818
import tornado
19-
except ImportError:
20-
raise RuntimeError("This example requires tornado.")
19+
except ImportError as err:
20+
raise RuntimeError("This example requires tornado.") from err
2121
import tornado.web
2222
import tornado.httpserver
2323
import tornado.ioloop

lib/matplotlib/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -656,10 +656,10 @@ def __setitem__(self, key, val):
656656
except ValueError as ve:
657657
raise ValueError(f"Key {key}: {ve}") from None
658658
dict.__setitem__(self, key, cval)
659-
except KeyError:
659+
except KeyError as err:
660660
raise KeyError(
661661
f"{key} is not a valid rc parameter (see rcParams.keys() for "
662-
f"a list of valid parameters)")
662+
f"a list of valid parameters)") from err
663663

664664
def __getitem__(self, key):
665665
if key in _deprecated_map:
@@ -942,9 +942,9 @@ def rc(group, **kwargs):
942942
key = '%s.%s' % (g, name)
943943
try:
944944
rcParams[key] = v
945-
except KeyError:
945+
except KeyError as err:
946946
raise KeyError(('Unrecognized key "%s" for group "%s" and '
947-
'name "%s"') % (key, g, name))
947+
'name "%s"') % (key, g, name)) from err
948948

949949

950950
def rcdefaults():

lib/matplotlib/axes/_axes.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4210,11 +4210,11 @@ def _parse_scatter_color_args(c, edgecolors, kwargs, xsize,
42104210
if kwcolor is not None:
42114211
try:
42124212
mcolors.to_rgba_array(kwcolor)
4213-
except ValueError:
4213+
except ValueError as err:
42144214
raise ValueError(
42154215
"'color' kwarg must be an color or sequence of color "
42164216
"specs. For a sequence of values to be color-mapped, use "
4217-
"the 'c' argument instead.")
4217+
"the 'c' argument instead.") from err
42184218
if edgecolors is None:
42194219
edgecolors = kwcolor
42204220
if facecolors is None:
@@ -4264,14 +4264,14 @@ def invalid_shape_exception(csize, xsize):
42644264
if not c_is_mapped:
42654265
try: # Is 'c' acceptable as PathCollection facecolors?
42664266
colors = mcolors.to_rgba_array(c)
4267-
except (TypeError, ValueError):
4267+
except (TypeError, ValueError) as err:
42684268
if not valid_shape:
4269-
raise invalid_shape_exception(c.size, xsize)
4269+
raise invalid_shape_exception(c.size, xsize) from err
42704270
# Both the mapping *and* the RGBA conversion failed: pretty
42714271
# severe failure => one may appreciate a verbose feedback.
42724272
raise ValueError(
42734273
f"'c' argument must be a color, a sequence of colors, or "
4274-
f"a sequence of numbers, not {c}")
4274+
f"a sequence of numbers, not {c}") from err
42754275
else:
42764276
if len(colors) not in (0, 1, xsize):
42774277
# NB: remember that a single color is also acceptable.

lib/matplotlib/axes/_base.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1732,10 +1732,10 @@ def axis(self, *args, emit=True, **kwargs):
17321732
limits = args[0]
17331733
try:
17341734
xmin, xmax, ymin, ymax = limits
1735-
except (TypeError, ValueError):
1735+
except (TypeError, ValueError) as err:
17361736
raise TypeError('the first argument to axis() must be an '
17371737
'interable of the form '
1738-
'[xmin, xmax, ymin, ymax]')
1738+
'[xmin, xmax, ymin, ymax]') from err
17391739
else:
17401740
xmin = kwargs.pop('xmin', None)
17411741
xmax = kwargs.pop('xmax', None)
@@ -2885,8 +2885,9 @@ def ticklabel_format(self, *, axis='both', style='', scilimits=None,
28852885
try:
28862886
m, n = scilimits
28872887
m + n + 1 # check that both are numbers
2888-
except (ValueError, TypeError):
2889-
raise ValueError("scilimits must be a sequence of 2 integers")
2888+
except (ValueError, TypeError) as err:
2889+
raise ValueError("scilimits must be a sequence of 2 integers"
2890+
) from err
28902891
STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None}
28912892
is_sci_style = cbook._check_getitem(STYLES, style=style)
28922893
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,
29042905
axis.major.formatter.set_useLocale(useLocale)
29052906
if useMathText is not None:
29062907
axis.major.formatter.set_useMathText(useMathText)
2907-
except AttributeError:
2908+
except AttributeError as err:
29082909
raise AttributeError(
2909-
"This method only works with the ScalarFormatter")
2910+
"This method only works with the ScalarFormatter") from err
29102911

29112912
def locator_params(self, axis='both', tight=None, **kwargs):
29122913
"""

lib/matplotlib/backends/backend_agg.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -143,15 +143,16 @@ def draw_path(self, gc, path, transform, rgbFace=None):
143143
p = Path(v, c)
144144
try:
145145
self._renderer.draw_path(gc, p, transform, rgbFace)
146-
except OverflowError:
147-
raise OverflowError("Exceeded cell block limit (set "
148-
"'agg.path.chunksize' rcparam)")
146+
except OverflowError as err:
147+
raise OverflowError(
148+
"Exceeded cell block limit (set 'agg.path.chunksize' "
149+
"rcparam)") from err
149150
else:
150151
try:
151152
self._renderer.draw_path(gc, path, transform, rgbFace)
152-
except OverflowError:
153+
except OverflowError as err:
153154
raise OverflowError("Exceeded cell block limit (set "
154-
"'agg.path.chunksize' rcparam)")
155+
"'agg.path.chunksize' rcparam)") from err
155156

156157
def draw_mathtext(self, gc, x, y, s, prop, angle):
157158
"""Draw mathtext using :mod:`matplotlib.mathtext`."""

lib/matplotlib/backends/backend_cairo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@
1818
except ImportError:
1919
try:
2020
import cairocffi as cairo
21-
except ImportError:
21+
except ImportError as err:
2222
raise ImportError(
2323
"cairo backend requires that pycairo>=1.11.0 or cairocffi"
24-
"is installed")
24+
"is installed") from err
2525

2626
from .. import cbook
2727
from matplotlib.backend_bases import (

lib/matplotlib/backends/backend_gtk3.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616

1717
try:
1818
import gi
19-
except ImportError:
20-
raise ImportError("The GTK3 backends require PyGObject")
19+
except ImportError as err:
20+
raise ImportError("The GTK3 backends require PyGObject") from err
2121

2222
try:
2323
# :raises ValueError: If module/version is already loaded, already
@@ -47,7 +47,7 @@
4747
except TypeError as exc:
4848
# Happens when running headless. Convert to ImportError to cooperate with
4949
# backend switching.
50-
raise ImportError(exc)
50+
raise ImportError(exc) from exc
5151

5252

5353
class TimerGTK3(TimerBase):

lib/matplotlib/backends/backend_nbagg.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,10 @@ def __init__(self, manager):
164164
display(HTML("<div id=%r></div>" % self.uuid))
165165
try:
166166
self.comm = Comm('matplotlib', data={'id': self.uuid})
167-
except AttributeError:
167+
except AttributeError as err:
168168
raise RuntimeError('Unable to create an IPython notebook Comm '
169-
'instance. Are you in the IPython notebook?')
169+
'instance. Are you in the IPython '
170+
'notebook?') from err
170171
self.comm.on_msg(self.on_message)
171172

172173
manager = self.manager

lib/matplotlib/backends/backend_pgf.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -273,13 +273,14 @@ def __init__(self):
273273
[self.texcommand, "-halt-on-error"],
274274
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
275275
encoding="utf-8", cwd=self.tmpdir)
276-
except FileNotFoundError:
276+
except FileNotFoundError as err:
277277
raise RuntimeError(
278278
f"{self.texcommand} not found. Install it or change "
279279
f"rcParams['pgf.texsystem'] to an available TeX "
280-
f"implementation.")
281-
except OSError:
282-
raise RuntimeError("Error starting process %r" % self.texcommand)
280+
f"implementation.") from err
281+
except OSError as err:
282+
raise RuntimeError("Error starting process %r" %
283+
self.texcommand) from err
283284
test_input = self.latex_header + latex_end
284285
stdout, stderr = latex.communicate(test_input)
285286
if latex.returncode != 0:
@@ -342,7 +343,7 @@ def get_width_height_descent(self, text, prop):
342343
self._expect_prompt()
343344
except LatexError as e:
344345
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
345-
.format(text, e.latex_output))
346+
.format(text, e.latex_output)) from e
346347

347348
# typeout width, height and text offset of the last textbox
348349
self._stdin_writeln(r"\typeout{\the\wd0,\the\ht0,\the\dp0}")
@@ -351,14 +352,14 @@ def get_width_height_descent(self, text, prop):
351352
answer = self._expect_prompt()
352353
except LatexError as e:
353354
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
354-
.format(text, e.latex_output))
355+
.format(text, e.latex_output)) from e
355356

356357
# parse metrics from the answer string
357358
try:
358359
width, height, offset = answer.splitlines()[0].split(",")
359-
except Exception:
360+
except Exception as err:
360361
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
361-
.format(text, answer))
362+
.format(text, answer)) from err
362363
w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])
363364

364365
# the height returned from LaTeX goes from base to top.

lib/matplotlib/backends/backend_ps.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1023,9 +1023,9 @@ def _print_figure_tex(
10231023
else:
10241024
try:
10251025
title = os.fspath(outfile)
1026-
except TypeError:
1026+
except TypeError as err:
10271027
raise ValueError(
1028-
"outfile must be a path or a file-like object")
1028+
"outfile must be a path or a file-like object") from err
10291029

10301030
self.figure.dpi = 72 # ignore the dpi kwarg
10311031
width, height = self.figure.get_size_inches()

lib/matplotlib/backends/backend_webagg.py

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

2626
try:
2727
import tornado
28-
except ImportError:
29-
raise RuntimeError("The WebAgg backend requires Tornado.")
28+
except ImportError as err:
29+
raise RuntimeError("The WebAgg backend requires Tornado.") from err
3030

3131
import tornado.web
3232
import tornado.ioloop

lib/matplotlib/backends/qt_compat.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,11 @@
5656
else:
5757
try:
5858
QT_API = _ETS[QT_API_ENV]
59-
except KeyError:
59+
except KeyError as err:
6060
raise RuntimeError(
6161
"The environment variable QT_API has the unrecognized value {!r};"
62-
"valid values are 'pyqt5', 'pyside2', 'pyqt', and 'pyside'")
62+
"valid values are 'pyqt5', 'pyside2', 'pyqt', and "
63+
"'pyside'") from err
6364

6465

6566
def _setup_pyqt5():

lib/matplotlib/cbook/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -721,11 +721,11 @@ def report_memory(i=0): # argument may go away
721721
def call(command, os_name):
722722
try:
723723
return subprocess.check_output(command)
724-
except subprocess.CalledProcessError:
724+
except subprocess.CalledProcessError as err:
725725
raise NotImplementedError(
726726
"report_memory works on %s only if "
727727
"the '%s' program is found" % (os_name, command[0])
728-
)
728+
) from err
729729

730730
pid = os.getpid()
731731
if sys.platform == 'sunos5':

lib/matplotlib/cm.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,9 @@ def register_cmap(name=None, cmap=None, data=None, lut=None):
100100
if name is None:
101101
try:
102102
name = cmap.name
103-
except AttributeError:
104-
raise ValueError("Arguments must include a name or a Colormap")
103+
except AttributeError as err:
104+
raise ValueError("Arguments must include a name or a "
105+
"Colormap") from err
105106
if isinstance(cmap, colors.Colormap):
106107
cmap_d[name] = cmap
107108
return

lib/matplotlib/collections.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -581,9 +581,9 @@ def set_linestyle(self, ls):
581581
except ValueError:
582582
dashes = [mlines._get_dash_pattern(x) for x in ls]
583583

584-
except ValueError:
585-
raise ValueError(
586-
'Do not know how to convert {!r} to dashes'.format(ls))
584+
except ValueError as err:
585+
raise ValueError('Do not know how to convert {!r} to '
586+
'dashes'.format(ls)) from err
587587

588588
# get the list of raw 'unscaled' dash patterns
589589
self._us_linestyles = dashes

lib/matplotlib/colorbar.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1038,9 +1038,9 @@ def _get_extension_lengths(self, frac, automin, automax, default=0.05):
10381038
# be encountered. This is an error.
10391039
if np.isnan(extendlength).any():
10401040
raise ValueError()
1041-
except (TypeError, ValueError):
1041+
except (TypeError, ValueError) as err:
10421042
# Raise an error on encountering an invalid value for frac.
1043-
raise ValueError('invalid value for extendfrac')
1043+
raise ValueError('invalid value for extendfrac') from err
10441044
return extendlength
10451045

10461046
def _uniform_y(self, N):

lib/matplotlib/colors.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -315,11 +315,11 @@ def to_rgba_array(c, alpha=None):
315315
# This is deprecated and will be removed in the future.
316316
try:
317317
result = np.array([to_rgba(cc, alpha) for cc in c])
318-
except ValueError:
318+
except ValueError as err:
319319
raise ValueError(
320320
"'%s' is neither a valid single color nor a color sequence "
321321
"consisting of single character color specifiers such as "
322-
"'rgb'. Note also that the latter is deprecated." % c)
322+
"'rgb'. Note also that the latter is deprecated." % c) from err
323323
else:
324324
cbook.warn_deprecated("3.2", message="Using a string of single "
325325
"character colors as a color sequence is "
@@ -443,8 +443,8 @@ def _create_lookup_table(N, data, gamma=1.0):
443443

444444
try:
445445
adata = np.array(data)
446-
except Exception:
447-
raise TypeError("data must be convertible to an array")
446+
except Exception as err:
447+
raise TypeError("data must be convertible to an array") from err
448448
shape = adata.shape
449449
if len(shape) != 2 or shape[1] != 3:
450450
raise ValueError("data must be nx3 format")
@@ -1894,9 +1894,9 @@ def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv',
18941894
else:
18951895
try:
18961896
blend = blend_mode(rgb, intensity, **kwargs)
1897-
except TypeError:
1897+
except TypeError as err:
18981898
raise ValueError('"blend_mode" must be callable or one of {}'
1899-
.format(lookup.keys))
1899+
.format(lookup.keys)) from err
19001900

19011901
# Only apply result where hillshade intensity isn't masked
19021902
if hasattr(intensity, 'mask'):

lib/matplotlib/font_manager.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -806,9 +806,9 @@ def set_stretch(self, stretch):
806806
stretch = int(stretch)
807807
if stretch < 0 or stretch > 1000:
808808
raise ValueError()
809-
except ValueError:
809+
except ValueError as err:
810810
if stretch not in stretch_dict:
811-
raise ValueError("stretch is invalid")
811+
raise ValueError("stretch is invalid") from err
812812
self._stretch = stretch
813813

814814
def set_size(self, size):
@@ -824,10 +824,10 @@ def set_size(self, size):
824824
except ValueError:
825825
try:
826826
scale = font_scalings[size]
827-
except KeyError:
827+
except KeyError as err:
828828
raise ValueError(
829829
"Size is invalid. Valid font size are "
830-
+ ", ".join(map(str, font_scalings)))
830+
+ ", ".join(map(str, font_scalings))) from err
831831
else:
832832
size = scale * FontManager.get_default_size()
833833
if size < 1.0:

lib/matplotlib/fontconfig_pattern.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def parse(self, pattern):
127127
self._parser.parseString(pattern)
128128
except self.ParseException as e:
129129
raise ValueError(
130-
"Could not parse font string: '%s'\n%s" % (pattern, e))
130+
"Could not parse font string: '%s'\n%s" % (pattern, e)) from e
131131

132132
self._properties = None
133133

0 commit comments

Comments
 (0)