Skip to content

Harmonize exceptions for unknown keyword arguments. #24889

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
Jan 7, 2023
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
3 changes: 3 additions & 0 deletions doc/api/next_api_changes/behavior/24889-AL.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
``AxesImage.set_extent`` now raises ``TypeError`` for unknown keyword arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It previously raised a `ValueError`.
17 changes: 17 additions & 0 deletions lib/matplotlib/_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,23 @@ def nargs_error(name, takes, given):
f"{given} were given")


def kwarg_error(name, kw):
"""
Generate a TypeError to be raised by function calls with wrong kwarg.

Parameters
----------
name : str
The name of the calling function.
kw : str or Iterable[str]
Either the invalid keyword argument name, or an iterable yielding
invalid keyword arguments (e.g., a ``kwargs`` dict).
"""
if not isinstance(kw, str):
kw = next(iter(kw))
return TypeError(f"{name}() got an unexpected keyword argument '{kw}'")


def recursive_subclasses(cls):
"""Yield *cls* and direct and indirect subclasses of *cls*."""
yield cls
Expand Down
9 changes: 3 additions & 6 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7795,8 +7795,7 @@ def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
extent = xmin, xmax, freqs[0], freqs[-1]

if 'origin' in kwargs:
raise TypeError("specgram() got an unexpected keyword argument "
"'origin'")
raise _api.kwarg_error("specgram", "origin")

im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax,
origin='upper', **kwargs)
Expand Down Expand Up @@ -7894,8 +7893,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'],
name='binary')
if 'interpolation' in kwargs:
raise TypeError(
"spy() got an unexpected keyword argument 'interpolation'")
raise _api.kwarg_error("spy", "interpolation")
if 'norm' not in kwargs:
kwargs['norm'] = mcolors.NoNorm()
ret = self.imshow(mask, interpolation='nearest',
Expand All @@ -7920,8 +7918,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
if markersize is None:
markersize = 10
if 'linestyle' in kwargs:
raise TypeError(
"spy() got an unexpected keyword argument 'linestyle'")
raise _api.kwarg_error("spy", "linestyle")
ret = mlines.Line2D(
x, y, linestyle='None', marker=marker, markersize=markersize,
**kwargs)
Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,7 @@ def __call__(self, *args, data=None, **kwargs):

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

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

def get_legend(self):
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -716,8 +716,7 @@ def add_subplot(self, *args, **kwargs):
if 'figure' in kwargs:
# Axes itself allows for a 'figure' kwarg, but since we want to
# bind the created Axes to self, it is not allowed here.
raise TypeError(
"add_subplot() got an unexpected keyword argument 'figure'")
raise _api.kwarg_error("add_subplot", "figure")

if (len(args) == 1
and isinstance(args[0], mpl.axes._base._AxesBase)
Expand Down
7 changes: 2 additions & 5 deletions lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -978,11 +978,8 @@ def set_extent(self, extent, **kwargs):
[("x", [extent[0], extent[1]]),
("y", [extent[2], extent[3]])],
kwargs)
if len(kwargs):
raise ValueError(
"set_extent did not consume all of the kwargs passed." +
f"{list(kwargs)!r} were unused"
)
if kwargs:
raise _api.kwarg_error("set_extent", kwargs)
xmin = self.axes._validate_converted_limits(
xmin, self.convert_xunits)
xmax = self.axes._validate_converted_limits(
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8244,7 +8244,7 @@ def test_automatic_legend():


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

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


Expand Down
4 changes: 1 addition & 3 deletions lib/matplotlib/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2069,9 +2069,7 @@ def set_params(self, **kwargs):
if 'integer' in kwargs:
self._integer = kwargs.pop('integer')
if kwargs:
key, _ = kwargs.popitem()
raise TypeError(
f"set_params() got an unexpected keyword argument '{key}'")
raise _api.kwarg_error("set_params", kwargs)

def _raw_ticks(self, vmin, vmax):
"""
Expand Down