Skip to content

Commit 498f462

Browse files
committed
Use repr in error messages
1 parent a2a1b0a commit 498f462

File tree

8 files changed

+63
-21
lines changed

8 files changed

+63
-21
lines changed

lib/matplotlib/axes/_base.py

Lines changed: 6 additions & 6 deletions
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 4 additions & 3 deletions
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

Lines changed: 6 additions & 6 deletions
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 22 additions & 1 deletion
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,26 @@ def test_empty_line_plots():
75747575
assert len(line) == 1
75757576

75767577

7578+
@pytest.mark.parametrize('err, fmt, match',
7579+
((ValueError, "foo",
7580+
"Unrecognized character f in format string 'foo'"),
7581+
(ValueError, "oo",
7582+
"Illegal format string 'oo'; two marker symbols"),
7583+
(ValueError, "::",
7584+
"Illegal format string '::'; two linestyle "
7585+
"symbols"),
7586+
(ValueError, "rr",
7587+
"Illegal format string 'rr'; two color symbols"),
7588+
(ValueError, ":o:r",
7589+
"Illegal format string ':o:r'; two linestyle "
7590+
"symbols"),
7591+
))
7592+
def test_plot_format_errors(err, fmt, match):
7593+
fig, ax = plt.subplots()
7594+
with pytest.raises(err, match=match):
7595+
ax.plot((0, 0), fmt)
7596+
7597+
75777598
def test_clim():
75787599
ax = plt.figure().add_subplot()
75797600
for plot_method in [

lib/matplotlib/tests/test_text.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,26 @@ 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],
257+
r"Unknown coordinate type: \[0, 0\]"),
258+
(ValueError, "foo",
259+
"'foo' is not a recognized coordinate"),
260+
(ValueError, "foo bar",
261+
"'foo bar' is not a recognized coordinate"),
262+
(ValueError, "offset foo",
263+
"xycoords cannot be an offset coordinate"),
264+
(ValueError, "axes foo",
265+
"'foo' is not a recognized unit"),
266+
))
267+
def test_annotate_errors(err, xycoords, match):
268+
fig, ax = plt.subplots()
269+
with pytest.raises(err, match=match):
270+
ax.annotate('xy', (0, 0), xytext=(0.5, 0.5), xycoords=xycoords)
271+
fig.canvas.draw()
272+
273+
254274
@image_comparison(['titles'])
255275
def test_titles():
256276
# left and right side titles

lib/matplotlib/text.py

Lines changed: 3 additions & 3 deletions
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)