Skip to content

Commit 85bb0be

Browse files
committed
Harmonize exceptions for unknown keyword arguments.
... via a kwarg_error helper (see nargs_error for a similar design). In particular the type of the exception thrown by AxesImage.set_extent changed, and parentheses were added to the error thrown by _process_plot_var_args.
1 parent ecf2c88 commit 85bb0be

File tree

8 files changed

+31
-23
lines changed

8 files changed

+31
-23
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
``AxesImage.set_extent`` now raises ``TypeError`` for unknown keyword arguments
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
It previously raised a `ValueError`.

lib/matplotlib/_api/__init__.py

+17
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,23 @@ def nargs_error(name, takes, given):
342342
f"{given} were given")
343343

344344

345+
def kwarg_error(name, kw):
346+
"""
347+
Generate a TypeError to be raised by function calls with wrong kwarg.
348+
349+
Parameters
350+
----------
351+
name : str
352+
The name of the calling function.
353+
kw : str or Iterable[str]
354+
Either the invalid keyword argument name, or an iterable yielding
355+
invalid keyword arguments (e.g., a ``kwargs`` dict).
356+
"""
357+
if not isinstance(kw, str):
358+
kw = next(iter(kw))
359+
return TypeError(f"{name}() got an unexpected keyword argument '{kw}'")
360+
361+
345362
def recursive_subclasses(cls):
346363
"""Yield *cls* and direct and indirect subclasses of *cls*."""
347364
yield cls

lib/matplotlib/axes/_axes.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -7795,8 +7795,7 @@ def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
77957795
extent = xmin, xmax, freqs[0], freqs[-1]
77967796

77977797
if 'origin' in kwargs:
7798-
raise TypeError("specgram() got an unexpected keyword argument "
7799-
"'origin'")
7798+
raise _api.kwarg_error("specgram", "origin")
78007799

78017800
im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax,
78027801
origin='upper', **kwargs)
@@ -7894,8 +7893,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
78947893
kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'],
78957894
name='binary')
78967895
if 'interpolation' in kwargs:
7897-
raise TypeError(
7898-
"spy() got an unexpected keyword argument 'interpolation'")
7896+
raise _api.kwarg_error("spy", "interpolation")
78997897
if 'norm' not in kwargs:
79007898
kwargs['norm'] = mcolors.NoNorm()
79017899
ret = self.imshow(mask, interpolation='nearest',
@@ -7920,8 +7918,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
79207918
if markersize is None:
79217919
markersize = 10
79227920
if 'linestyle' in kwargs:
7923-
raise TypeError(
7924-
"spy() got an unexpected keyword argument 'linestyle'")
7921+
raise _api.kwarg_error("spy", "linestyle")
79257922
ret = mlines.Line2D(
79267923
x, y, linestyle='None', marker=marker, markersize=markersize,
79277924
**kwargs)

lib/matplotlib/axes/_base.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -243,8 +243,7 @@ def __call__(self, *args, data=None, **kwargs):
243243

244244
for pos_only in "xy":
245245
if pos_only in kwargs:
246-
raise TypeError("{} got an unexpected keyword argument {!r}"
247-
.format(self.command, pos_only))
246+
raise _api.kwarg_error(self.command, pos_only)
248247

249248
if not args:
250249
return
@@ -2188,8 +2187,7 @@ def axis(self, arg=None, /, *, emit=True, **kwargs):
21882187
self.set_xlim(xmin, xmax, emit=emit, auto=xauto)
21892188
self.set_ylim(ymin, ymax, emit=emit, auto=yauto)
21902189
if kwargs:
2191-
raise TypeError(f"axis() got an unexpected keyword argument "
2192-
f"'{next(iter(kwargs))}'")
2190+
raise _api.kwarg_error("axis", kwargs)
21932191
return (*self.get_xlim(), *self.get_ylim())
21942192

21952193
def get_legend(self):

lib/matplotlib/figure.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -716,8 +716,7 @@ def add_subplot(self, *args, **kwargs):
716716
if 'figure' in kwargs:
717717
# Axes itself allows for a 'figure' kwarg, but since we want to
718718
# bind the created Axes to self, it is not allowed here.
719-
raise TypeError(
720-
"add_subplot() got an unexpected keyword argument 'figure'")
719+
raise _api.kwarg_error("add_subplot", "figure")
721720

722721
if (len(args) == 1
723722
and isinstance(args[0], mpl.axes._base._AxesBase)

lib/matplotlib/image.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -978,11 +978,8 @@ def set_extent(self, extent, **kwargs):
978978
[("x", [extent[0], extent[1]]),
979979
("y", [extent[2], extent[3]])],
980980
kwargs)
981-
if len(kwargs):
982-
raise ValueError(
983-
"set_extent did not consume all of the kwargs passed." +
984-
f"{list(kwargs)!r} were unused"
985-
)
981+
if kwargs:
982+
raise _api.kwarg_error("set_extent", kwargs)
986983
xmin = self.axes._validate_converted_limits(
987984
xmin, self.convert_xunits)
988985
xmax = self.axes._validate_converted_limits(

lib/matplotlib/tests/test_axes.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -8244,7 +8244,7 @@ def test_automatic_legend():
82448244

82458245

82468246
def test_plot_errors():
8247-
with pytest.raises(TypeError, match="plot got an unexpected keyword"):
8247+
with pytest.raises(TypeError, match=r"plot\(\) got an unexpected keyword"):
82488248
plt.plot([1, 2, 3], x=1)
82498249
with pytest.raises(ValueError, match=r"plot\(\) with multiple groups"):
82508250
plt.plot([1, 2, 3], [1, 2, 3], [2, 3, 4], [2, 3, 4], label=['1', '2'])
@@ -8419,8 +8419,7 @@ def test_extent_units():
84198419
axs[1, 1].xaxis.set_major_formatter(mdates.DateFormatter('%d'))
84208420
axs[1, 1].set(xlabel='Day of Jan 2020')
84218421

8422-
with pytest.raises(ValueError,
8423-
match="set_extent did not consume all of the kwargs"):
8422+
with pytest.raises(TypeError, match=r"set_extent\(\) got an unexpected"):
84248423
im.set_extent([2, 12, date_first, date_last], clip=False)
84258424

84268425

lib/matplotlib/ticker.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -2069,9 +2069,7 @@ def set_params(self, **kwargs):
20692069
if 'integer' in kwargs:
20702070
self._integer = kwargs.pop('integer')
20712071
if kwargs:
2072-
key, _ = kwargs.popitem()
2073-
raise TypeError(
2074-
f"set_params() got an unexpected keyword argument '{key}'")
2072+
raise _api.kwarg_error("set_params", kwargs)
20752073

20762074
def _raw_ticks(self, vmin, vmax):
20772075
"""

0 commit comments

Comments
 (0)