Skip to content

Use repr in error messages #22712

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
Apr 7, 2022
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
12 changes: 6 additions & 6 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,25 +169,25 @@ def _process_plot_format(fmt):
if fmt[i:i+2] in mlines.lineStyles: # First, the two-char styles.
if linestyle is not None:
raise ValueError(
'Illegal format string "%s"; two linestyle symbols' % fmt)
f'Illegal format string {fmt!r}; two linestyle symbols')
linestyle = fmt[i:i+2]
i += 2
elif c in mlines.lineStyles:
if linestyle is not None:
raise ValueError(
'Illegal format string "%s"; two linestyle symbols' % fmt)
f'Illegal format string {fmt!r}; two linestyle symbols')
linestyle = c
i += 1
elif c in mlines.lineMarkers:
if marker is not None:
raise ValueError(
'Illegal format string "%s"; two marker symbols' % fmt)
f'Illegal format string {fmt!r}; two marker symbols')
marker = c
i += 1
elif c in mcolors.get_named_colors_mapping():
if color is not None:
raise ValueError(
'Illegal format string "%s"; two color symbols' % fmt)
f'Illegal format string {fmt!r}; two color symbols')
color = c
i += 1
elif c == 'C' and i < len(fmt) - 1:
Expand Down Expand Up @@ -2084,8 +2084,8 @@ def axis(self, *args, emit=True, **kwargs):
self.set_ylim([ylim[0], ylim[0] + edge_size],
emit=emit, auto=False)
else:
raise ValueError('Unrecognized string %s to axis; '
'try on or off' % s)
raise ValueError(f"Unrecognized string {s!r} to axis; "
"try 'on' or 'off'")
else:
if len(args) == 1:
limits = args[0]
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -1764,7 +1764,7 @@ def _set_transforms(self):
elif self._units == 'dots':
sc = 1.0
else:
raise ValueError('unrecognized units: %s' % self._units)
raise ValueError(f'Unrecognized units: {self._units!r}')

self._transforms = np.zeros((len(self._widths), 3, 3))
widths = self._widths * sc
Expand Down
7 changes: 4 additions & 3 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -1469,7 +1469,7 @@ def _make_verts(self):
coords = np.concatenate([left_half_arrow[:-1],
right_half_arrow[-2::-1]])
else:
raise ValueError("Got unknown shape: %s" % self.shape)
raise ValueError(f"Got unknown shape: {self._shape!r}")
if distance != 0:
cx = self._dx / distance
sx = self._dy / distance
Expand Down Expand Up @@ -2191,12 +2191,13 @@ def __new__(cls, stylename, **kwargs):
try:
_cls = cls._style_list[_name]
except KeyError as err:
raise ValueError(f"Unknown style: {stylename}") from err
raise ValueError(f"Unknown style: {stylename!r}") from err
try:
_args_pair = [cs.split("=") for cs in _list[1:]]
_args = {k: float(v) for k, v in _args_pair}
except ValueError as err:
raise ValueError(f"Incorrect style argument: {stylename}") from err
raise ValueError(
f"Incorrect style argument: {stylename!r}") from err
return _cls(**{**_args, **kwargs})

@classmethod
Expand Down
12 changes: 6 additions & 6 deletions lib/matplotlib/rcsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def validate_bool(b):
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
return False
else:
raise ValueError('Could not convert "%s" to bool' % b)
raise ValueError(f'Cannot convert {b!r} to bool')


def validate_axisbelow(s):
Expand All @@ -156,8 +156,8 @@ def validate_axisbelow(s):
if isinstance(s, str):
if s == 'line':
return 'line'
raise ValueError('%s cannot be interpreted as'
' True, False, or "line"' % s)
raise ValueError(f'{s!r} cannot be interpreted as'
' True, False, or "line"')


def validate_dpi(s):
Expand Down Expand Up @@ -739,14 +739,14 @@ def validate_cycler(s):
_DunderChecker().visit(ast.parse(s))
s = eval(s, {'cycler': cycler, '__builtins__': {}})
except BaseException as e:
raise ValueError("'%s' is not a valid cycler construction: %s" %
(s, e)) from e
raise ValueError(f"{s!r} is not a valid cycler construction: {e}"
) from e
# Should make sure what comes from the above eval()
# is a Cycler object.
if isinstance(s, Cycler):
cycler_inst = s
else:
raise ValueError("object was not a string or Cycler instance: %s" % s)
raise ValueError(f"Object is not a string or Cycler instance: {s!r}")

unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases))
if unknowns:
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/sphinxext/plot_directive.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def _option_boolean(arg):
elif arg.strip().lower() in ('yes', '1', 'true'):
return True
else:
raise ValueError('"%s" unknown boolean' % arg)
raise ValueError(f'{arg!r} unknown boolean')


def _option_context(arg):
Expand Down
16 changes: 15 additions & 1 deletion lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5095,7 +5095,8 @@ def test_shared_aspect_error():
r"axis\(\) takes 0 or 1 positional arguments but 2"
" were given"),
(ValueError, ('foo', ), {},
"Unrecognized string foo to axis; try on or off"),
"Unrecognized string 'foo' to axis; try 'on' or "
"'off'"),
(TypeError, ([1, 2], ), {},
"the first argument to axis*"),
(TypeError, tuple(), {'foo': None},
Expand Down Expand Up @@ -7574,6 +7575,19 @@ def test_empty_line_plots():
assert len(line) == 1


@pytest.mark.parametrize('fmt, match', (
("foo", "Unrecognized character f in format string 'foo'"),
("o+", "Illegal format string 'o\\+'; two marker symbols"),
(":-", "Illegal format string ':-'; two linestyle symbols"),
("rk", "Illegal format string 'rk'; two color symbols"),
(":o-r", "Illegal format string ':o-r'; two linestyle symbols"),
))
def test_plot_format_errors(fmt, match):
fig, ax = plt.subplots()
with pytest.raises(ValueError, match=match):
ax.plot((0, 0), fmt)


def test_clim():
ax = plt.figure().add_subplot()
for plot_method in [
Expand Down
16 changes: 15 additions & 1 deletion lib/matplotlib/tests/test_patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import matplotlib as mpl
from matplotlib.patches import (Annulus, Ellipse, Patch, Polygon, Rectangle,
FancyArrowPatch)
FancyArrowPatch, FancyArrow, BoxStyle)
from matplotlib.testing.decorators import image_comparison, check_figures_equal
from matplotlib.transforms import Bbox
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -692,6 +692,20 @@ def test_rotated_arcs():
ax.set_aspect("equal")


def test_fancyarrow_shape_error():
with pytest.raises(ValueError, match="Got unknown shape: 'foo'"):
FancyArrow(0, 0, 0.2, 0.2, shape='foo')


@pytest.mark.parametrize('fmt, match', (
("foo", "Unknown style: 'foo'"),
("Round,foo", "Incorrect style argument: 'Round,foo'"),
))
def test_boxstyle_errors(fmt, match):
with pytest.raises(ValueError, match=match):
BoxStyle(fmt)


@image_comparison(baseline_images=['annulus'], extensions=['png'])
def test_annulus():

Expand Down
15 changes: 15 additions & 0 deletions lib/matplotlib/tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,21 @@ def test_annotation_contains():
assert ann.contains(event) == (False, {})


@pytest.mark.parametrize('err, xycoords, match', (
(RuntimeError, print, "Unknown return type"),
(RuntimeError, [0, 0], r"Unknown coordinate type: \[0, 0\]"),
(ValueError, "foo", "'foo' is not a recognized coordinate"),
(ValueError, "foo bar", "'foo bar' is not a recognized coordinate"),
(ValueError, "offset foo", "xycoords cannot be an offset coordinate"),
(ValueError, "axes foo", "'foo' is not a recognized unit"),
))
def test_annotate_errors(err, xycoords, match):
fig, ax = plt.subplots()
with pytest.raises(err, match=match):
ax.annotate('xy', (0, 0), xytext=(0.5, 0.5), xycoords=xycoords)
fig.canvas.draw()


@image_comparison(['titles'])
def test_titles():
# left and right side titles
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -1466,7 +1466,7 @@ def _get_xy_transform(self, renderer, s):

s_ = s.split()
if len(s_) != 2:
raise ValueError("%s is not a recognized coordinate" % s)
raise ValueError(f"{s!r} is not a recognized coordinate")

bbox0, xy0 = None, None

Expand Down Expand Up @@ -1506,12 +1506,12 @@ def _get_xy_transform(self, renderer, s):
w, h = bbox0.size
tr = Affine2D().scale(w, h)
else:
raise ValueError("%s is not a recognized coordinate" % s)
raise ValueError(f"{unit!r} is not a recognized unit")

return tr.translate(ref_x, ref_y)

else:
raise ValueError("%s is not a recognized coordinate" % s)
raise ValueError(f"{s!r} is not a recognized coordinate")

def _get_ref_xy(self, renderer):
"""
Expand Down