8000 Merge pull request #24889 from anntzer/ke · matplotlib/matplotlib@d12ea34 · GitHub
[go: up one dir, main page]

Skip to content

Commit d12ea34

Browse files
authored
Merge pull request #24889 from anntzer/ke
Harmonize exceptions for unknown keyword arguments.
2 parents 5ead278 + 85bb0be commit d12ea34

File tree

8 files changed

+31
-23
lines changed

8 files changed

+31
-23
lines changed
Lines changed: 3 additions & 0 deletions
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

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

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7787,8 +7787,7 @@ def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
77877787
extent = xmin, xmax, freqs[0], freqs[-1]
77887788

77897789
if 'origin' in kwargs:
7790-
raise TypeError("specgram() got an unexpected keyword argument "
7791-
"'origin'")
7790+
raise _api.kwarg_error("specgram", "origin")
77927791

77937792
im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax,
77947793
origin='upper', **kwargs)
@@ -7886,8 +7885,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
78867885
kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'],
78877886
name='binary')
78887887
if 'interpolation' in kwargs:
7889-
raise TypeError(
7890-
"spy() got an unexpected keyword argument 'interpolation'")
7888+
raise _api.kwarg_error("spy", "interpolation")
78917889
if 'norm' not in kwargs:
78927890
kwargs['norm'] = mcolors.NoNorm()
78937891
ret = self.imshow(mask, interpolation='nearest',
@@ -7912,8 +7910,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
79127910
if markersize is None:
79137911
markersize = 10
79147912
if 'linestyle' in kwargs:
7915-
raise TypeError(
7916-
"spy() got an unexpected keyword argument 'linestyle'")
7913+
raise _api.kwarg_error("spy", "linestyle")
79177914
ret = mlines.Line2D(
79187915
x, y, linestyle='None', marker=marker, markersize=markersize,
79197916
**kwargs)

lib/matplotlib/axes/_base.py

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

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

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8248,7 +8248,7 @@ def test_automatic_legend():
82488248

82498249

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

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

84308429

lib/matplotlib/ticker.py

Lines changed: 1 addition & 3 deletions
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)
0