Skip to content

Commit 22a44db

Browse files
committed
Use repr in error messages
1 parent 8b1881f commit 22a44db

File tree

9 files changed

+66
-22
lines changed

9 files changed

+66
-22
lines changed

lib/matplotlib/axes/_base.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -169,25 +169,25 @@ def _process_plot_format(fmt):
169169
if fmt[i:i+2] in mlines.lineStyles: # First, the two-char styles.
170170
if linestyle is not None:
171171
raise ValueError(
172-
'Illegal format string "%s"; two linestyle symbols' % fmt)
172+
f'Illegal format string {fmt!r}; two linestyle symbols')
173173
linestyle = fmt[i:i+2]
174174
i += 2
175175
elif c in mlines.lineStyles:
176176
if linestyle is not None:
177177
raise ValueError(
178-
'Illegal format string "%s"; two linestyle symbols' % fmt)
178+
f'Illegal format string {fmt!r}; two linestyle symbols')
179179
linestyle = c
180180
i += 1
181181
elif c in mlines.lineMarkers:
182182
if marker is not None:
183183
raise ValueError(
184-
'Illegal format string "%s"; two marker symbols' % fmt)
184+
f'Illegal format string {fmt!r}; two marker symbols')
185185
marker = c
186186
i += 1
187187
elif c in mcolors.get_named_colors_mapping():
188188
if color is not None:
189189
raise ValueError(
190-
'Illegal format string "%s"; two color symbols' % fmt)
190+
f'Illegal format string {fmt!r}; two color symbols')
191191
color = c
192192
i += 1
193193
elif c == 'C' and i < len(fmt) - 1:
@@ -2084,8 +2084,8 @@ def axis(self, *args, emit=True, **kwargs):
20842084
self.set_ylim([ylim[0], ylim[0] + edge_size],
20852085
emit=emit, auto=False)
20862086
else:
2087-
raise ValueError('Unrecognized string %s to axis; '
2088-
'try on or off' % s)
2087+
raise ValueError(f"Unrecognized string {s!r} to axis; "
2088+
"try 'on' or 'off'")
20892089
else:
20902090
if len(args) == 1:
20912091
limits = args[0]

lib/matplotlib/collections.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1764,7 +1764,7 @@ def _set_transforms(self):
17641764
elif self._units == 'dots':
17651765
sc = 1.0
17661766
else:
1767-
raise ValueError('unrecognized units: %s' % self._units)
1767+
raise ValueError(f'Unrecognized units: {self._units!r}')
17681768

17691769
self._transforms = np.zeros((len(self._widths), 3, 3))
17701770
widths = self._widths * sc

lib/matplotlib/patches.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1469,7 +1469,7 @@ def _make_verts(self):
14691469
coords = np.concatenate([left_half_arrow[:-1],
14701470
right_half_arrow[-2::-1]])
14711471
else:
1472-
raise ValueError("Got unknown shape: %s" % self.shape)
1472+
raise ValueError(f"Got unknown shape: {self._shape!r}")
14731473
if distance != 0:
14741474
cx = self._dx / distance
14751475
sx = self._dy / distance
@@ -2191,12 +2191,13 @@ def __new__(cls, stylename, **kwargs):
21912191
try:
21922192
_cls = cls._style_list[_name]
21932193
except KeyError as err:
2194-
raise ValueError(f"Unknown style: {stylename}") from err
2194+
raise ValueError(f"Unknown style: {stylename!r}") from err
21952195
try:
21962196
_args_pair = [cs.split("=") for cs in _list[1:]]
21972197
_args = {k: float(v) for k, v in _args_pair}
21982198
except ValueError as err:
2199-
raise ValueError(f"Incorrect style argument: {stylename}") from err
2199+
raise ValueError(
2200+
f"Incorrect style argument: {stylename!r}") from err
22002201
return _cls(**{**_args, **kwargs})
22012202

22022203
@classmethod

lib/matplotlib/rcsetup.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def validate_bool(b):
146146
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
147147
return False
148148
else:
149-
raise ValueError('Could not convert "%s" to bool' % b)
149+
raise ValueError(f'Cannot convert {b!r} to bool')
150150

151151

152152
def validate_axisbelow(s):
@@ -156,8 +156,8 @@ def validate_axisbelow(s):
156156
if isinstance(s, str):
157157
if s == 'line':
158158
return 'line'
159-
raise ValueError('%s cannot be interpreted as'
160-
' True, False, or "line"' % s)
159+
raise ValueError(f'{s!r} cannot be interpreted as'
160+
' True, False, or "line"')
161161

162162

163163
def validate_dpi(s):
@@ -739,14 +739,14 @@ def validate_cycler(s):
739739
_DunderChecker().visit(ast.parse(s))
740740
s = eval(s, {'cycler': cycler, '__builtins__': {}})
741741
except BaseException as e:
742-
raise ValueError("'%s' is not a valid cycler construction: %s" %
743-
(s, e)) from e
742+
raise ValueError(f"{s!r} is not a valid cycler construction: {e}"
743+
) from e
744744
# Should make sure what comes from the above eval()
745745
# is a Cycler object.
746746
if isinstance(s, Cycler):
747747
cycler_inst = s
748748
else:
749-
raise ValueError("object was not a string or Cycler instance: %s" % s)
749+
raise ValueError(f"Object is not a string or Cycler instance: {s!r}")
750750

751751
unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases))
752752
if unknowns:

lib/matplotlib/sphinxext/plot_directive.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ def _option_boolean(arg):
183183
elif arg.strip().lower() in ('yes', '1', 'true'):
184184
return True
185185
else:
186-
raise ValueError('"%s" unknown boolean' % arg)
186+
raise ValueError(f'{arg!r} unknown boolean')
187187

188188

189189
def _option_context(arg):

lib/matplotlib/tests/test_axes.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -5095,7 +5095,8 @@ def test_shared_aspect_error():
50955095
r"axis\(\) takes 0 or 1 positional arguments but 2"
50965096
" were given"),
50975097
(ValueError, ('foo', ), {},
5098-
"Unrecognized string foo to axis; try on or off"),
5098+
"Unrecognized string 'foo' to axis; try 'on' or "
5099+
"'off'"),
50995100
(TypeError, ([1, 2], ), {},
51005101
"the first argument to axis*"),
51015102
(TypeError, tuple(), {'foo': None},
@@ -7574,6 +7575,19 @@ def test_empty_line_plots():
75747575
assert len(line) == 1
75757576

75767577

7578+
@pytest.mark.parametrize('fmt, match', (
7579+
("foo", "Unrecognized character f in format string 'foo'"),
7580+
("o+", "Illegal format string 'o\\+'; two marker symbols"),
7581+
(":-", "Illegal format string ':-'; two linestyle symbols"),
7582+
("rk", "Illegal format string 'rk'; two color symbols"),
7583+
(":o-r", "Illegal format string ':o-r'; two linestyle symbols"),
7584+
))
7585+
def test_plot_format_errors(fmt, match):
7586+
fig, ax = plt.subplots()
7587+
with pytest.raises(ValueError, match=match):
7588+
ax.plot((0, 0), fmt)
7589+
7590+
75777591
def test_clim():
75787592
ax = plt.figure().add_subplot()
75797593
for plot_method in [

lib/matplotlib/tests/test_patches.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import matplotlib as mpl
99
from matplotlib.patches import (Annulus, Ellipse, Patch, Polygon, Rectangle,
10-
FancyArrowPatch)
10+
FancyArrowPatch, FancyArrow, BoxStyle)
1111
from matplotlib.testing.decorators import image_comparison, check_figures_equal
1212
from matplotlib.transforms import Bbox
1313
import matplotlib.pyplot as plt
@@ -692,6 +692,20 @@ def test_rotated_arcs():
692692
ax.set_aspect("equal")
693693

694694

695+
def test_fancyarrow_shape_error():
696+
with pytest.raises(ValueError, match="Got unknown shape: 'foo'"):
697+
FancyArrow(0, 0, 0.2, 0.2, shape='foo')
698+
699+
700+
@pytest.mark.parametrize('fmt, match', (
701+
("foo", "Unknown style: 'foo'"),
702+
("Round,foo", "Incorrect style argument: 'Round,foo'"),
703+
))
704+
def test_boxstyle_errors(fmt, match):
705+
with pytest.raises(ValueError, match=match):
706+
BoxStyle(fmt)
707+
708+
695709
@image_comparison(baseline_images=['annulus'], extensions=['png'])
696710
def test_annulus():
697711

lib/matplotlib/tests/test_text.py

+15
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,21 @@ def test_annotation_contains():
251251
assert ann.contains(event) == (False, {})
252252

253253

254+
@pytest.mark.parametrize('err, xycoords, match', (
255+
(RuntimeError, print, "Unknown return type"),
256+
(RuntimeError, [0, 0], r"Unknown coordinate type: \[0, 0\]"),
257+
(ValueError, "foo", "'foo' is not a recognized coordinate"),
258+
(ValueError, "foo bar", "'foo bar' is not a recognized coordinate"),
259+
(ValueError, "offset foo", "xycoords cannot be an offset coordinate"),
260+
(ValueError, "axes foo", "'foo' is not a recognized unit"),
261+
))
262+
def test_annotate_errors(err, xycoords, match):
263+
fig, ax = plt.subplots()
264+
with pytest.raises(err, match=match):
265+
ax.annotate('xy', (0, 0), xytext=(0.5, 0.5), xycoords=xycoords)
266+
fig.canvas.draw()
267+
268+
254269
@image_comparison(['titles'])
255270
def test_titles():
256271
# left and right side titles

lib/matplotlib/text.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1466,7 +1466,7 @@ def _get_xy_transform(self, renderer, s):
14661466

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

14711471
bbox0, xy0 = None, None
14721472

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

15111511
return tr.translate(ref_x, ref_y)
15121512

15131513
else:
1514-
raise ValueError("%s is not a recognized coordinate" % s)
1514+
raise ValueError(f"{s!r} is not a recognized coordinate")
15151515

15161516
def _get_ref_xy(self, renderer):
15171517
"""

0 commit comments

Comments
 (0)