Skip to content

Commit 985c73d

Browse files
committed
Use repr in error messages
1 parent 5971feb commit 985c73d

File tree

10 files changed

+71
-30
lines changed

10 files changed

+71
-30
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/legend.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -558,8 +558,8 @@ def val_or_rc(val, rc_name):
558558
colors.to_rgba_array(labelcolor))):
559559
text.set_color(color)
560560
else:
561-
raise ValueError("Invalid argument for labelcolor : %s" %
562-
str(labelcolor))
561+
raise ValueError("Invalid argument for labelcolor: "
562+
f"{labelcolor!r}")
563563

564564
def _set_artist_props(self, a):
565565
"""
@@ -943,8 +943,8 @@ def set_bbox_to_anchor(self, bbox, transform=None):
943943
try:
944944
l = len(bbox)
945945
except TypeError as err:
946-
raise ValueError("Invalid argument for bbox : %s" %
947-
str(bbox)) from err
946+
raise ValueError(f"Invalid argument for bbox: {bbox!r}") \
947+
from err
948948

949949
if l == 2:
950950
bbox = [bbox[0], bbox[1], 0, 0]

lib/matplotlib/offsetbox.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,8 +1064,8 @@ def set_bbox_to_anchor(self, bbox, transform=None):
10641064
try:
10651065
l = len(bbox)
10661066
except TypeError as err:
1067-
raise ValueError("Invalid argument for bbox : %s" %
1068-
str(bbox)) from err
1067+
raise ValueError(f"Invalid argument for bbox: {bbox!r}") \
1068+
from err
10691069

10701070
if l == 2:
10711071
bbox = [bbox[0], bbox[1], 0, 0]

lib/matplotlib/patches.py

Lines changed: 4 additions & 4 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
@@ -2192,14 +2192,14 @@ def __new__(cls, stylename, **kwargs):
21922192
try:
21932193
_cls = cls._style_list[_name]
21942194
except KeyError as err:
2195-
raise ValueError("Unknown style : %s" % stylename) from err
2195+
raise ValueError(f"Unknown style: {stylename!r}") from err
21962196

21972197
try:
21982198
_args_pair = [cs.split("=") for cs in _list[1:]]
21992199
_args = {k: float(v) for k, v in _args_pair}
22002200
except ValueError as err:
2201-
raise ValueError("Incorrect style argument : %s" %
2202-
stylename) from err
2201+
raise ValueError(f"Incorrect style argument: {stylename!r}") \
2202+
from err
22032203
_args.update(kwargs)
22042204

22052205
return _cls(**_args)

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
@@ -5093,7 +5093,8 @@ def test_shared_aspect_error():
50935093
r"axis\(\) takes 0 or 1 positional arguments but 2"
50945094
" were given"),
50955095
(ValueError, ('foo', ), {},
5096-
"Unrecognized string foo to axis; try on or off"),
5096+
"Unrecognized string 'foo' to axis; try 'on' or "
5097+
"'off'"),
50975098
(TypeError, ([1, 2], ), {},
50985099
"the first argument to axis*"),
50995100
(TypeError, tuple(), {'foo': None},
@@ -7572,6 +7573,26 @@ def test_empty_line_plots():
75727573
assert len(line) == 1
75737574

75747575

7576+
@pytest.mark.parametrize('err, fmt, match',
7577+
((ValueError, "foo",
7578+
"Unrecognized character f in format string 'foo'"),
7579+
(ValueError, "oo",
7580+
"Illegal format string 'oo'; two marker symbols"),
7581+
(ValueError, "::",
7582+
"Illegal format string '::'; two linestyle "
7583+
"symbols"),
7584+
(ValueError, "rr",
7585+
"Illegal format string 'rr'; two color symbols"),
7586+
(ValueError, ":o:r",
7587+
"Illegal format string ':o:r'; two linestyle "
7588+
"symbols"),
7589+
))
7590+
def test_plot_format_errors(err, fmt, match):
7591+
fig, ax = plt.subplots()
7592+
with pytest.raises(err, match=match):
7593+
ax.plot((0, 0), fmt)
7594+
7595+
75757596
def test_clim():
75767597
ax = plt.figure().add_subplot()
75777598
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: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1443,7 +1443,7 @@ def _get_xy_transform(self, renderer, s):
14431443
elif isinstance(tr, Transform):
14441444
return tr
14451445
else:
1446-
raise RuntimeError("unknown return type ...")
1446+
raise RuntimeError("Unknown return type...")
14471447
elif isinstance(s, Artist):
14481448
bbox = s.get_window_extent(renderer)
14491449
return BboxTransformTo(bbox)
@@ -1452,7 +1452,7 @@ def _get_xy_transform(self, renderer, s):
14521452
elif isinstance(s, Transform):
14531453
return s
14541454
elif not isinstance(s, str):
1455-
raise RuntimeError("unknown coordinate type : %s" % s)
1455+
raise RuntimeError(f"Unknown coordinate type: {s!r}")
14561456

14571457
if s == 'data':
14581458
return self.axes.transData
@@ -1464,7 +1464,7 @@ def _get_xy_transform(self, renderer, s):
14641464

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

14691469
bbox0, xy0 = None, None
14701470

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

15091509
return tr.translate(ref_x, ref_y)
15101510

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

15141514
def _get_ref_xy(self, renderer):
15151515
"""

0 commit comments

Comments
 (0)