Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Factor out error generation for function calls with wrong nargs. #24447

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
Nov 14, 2022
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
6 changes: 6 additions & 0 deletions lib/matplotlib/_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,12 @@ def my_func(*args, **kwargs):
raise


def nargs_error(name, takes, given):
"""Generate a TypeError to be raised by function calls with wrong arity."""
return TypeError(f"{name}() takes {takes} positional arguments but "
f"{given} were given")


def recursive_subclasses(cls):
"""Yield *cls* and direct and indirect subclasses of *cls*."""
yield cls
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5695,8 +5695,7 @@ def _pcolorargs(self, funcname, *args, shading='auto', **kwargs):
Y = Y.data
nrows, ncols = C.shape
else:
raise TypeError(f'{funcname}() takes 1 or 3 positional arguments '
f'but {len(args)} were given')
raise _api.nargs_error(funcname, takes="1 or 3", given=len(args))

Nx = X.shape[-1]
Ny = Y.shape[0]
Expand Down
9 changes: 4 additions & 5 deletions lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -1444,17 +1444,16 @@ def _contour_args(self, args, kwargs):
fn = 'contourf'
else:
fn = 'contour'
Nargs = len(args)
if Nargs <= 2:
nargs = len(args)
if nargs <= 2:
z = ma.asarray(args[0], dtype=np.float64)
x, y = self._initialize_x_y(z)
args = args[1:]
elif Nargs <= 4:
elif nargs <= 4:
x, y, z = self._check_xyz(args[:3], kwargs)
args = args[3:]
else:
raise TypeError("Too many arguments to %s; see help(%s)" %
(fn, fn))
raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)
z = ma.masked_invalid(z, copy=False)
self.zmax = float(z.max())
self.zmin = float(z.min())
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/gridspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,8 +587,7 @@ def _from_subplot_args(figure, args):
elif len(args) == 3:
rows, cols, num = args
else:
raise TypeError(f"subplot() takes 1 or 3 positional arguments but "
f"{len(args)} were given")
raise _api.nargs_error("subplot", takes="1 or 3", given=len(args))

gs = GridSpec._check_gridspec_exists(figure, rows, cols)
if gs is None:
Expand Down
17 changes: 8 additions & 9 deletions lib/matplotlib/quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,20 +406,19 @@ def _parse_args(*args, caller_name='function'):
"""
X = Y = C = None

len_args = len(args)
if len_args == 2:
nargs = len(args)
if nargs == 2:
# The use of atleast_1d allows for handling scalar arguments while also
# keeping masked arrays
U, V = np.atleast_1d(*args)
elif len_args == 3:
elif nargs == 3:
U, V, C = np.atleast_1d(*args)
elif len_args == 4:
elif nargs == 4:
X, Y, U, V = np.atleast_1d(*args)
elif len_args == 5:
elif nargs == 5:
X, Y, U, V, C = np.atleast_1d(*args)
else:
raise TypeError(f'{caller_name} takes 2-5 positional arguments but '
f'{len_args} were given')
raise _api.nargs_error(caller_name, takes="from 2 to 5", given=nargs)

nr, nc = (1, U.shape[0]) if U.ndim == 1 else U.shape

Expand Down Expand Up @@ -476,7 +475,7 @@ def __init__(self, ax, *args,
%s
"""
self._axes = ax # The attr actually set by the Artist.axes property.
X, Y, U, V, C = _parse_args(*args, caller_name='quiver()')
X, Y, U, V, C = _parse_args(*args, caller_name='quiver')
self.X = X
self.Y = Y
self.XY = np.column_stack((X, Y))
Expand Down Expand Up @@ -928,7 +927,7 @@ def __init__(self, ax, *args,
kwargs['linewidth'] = 1

# Parse out the data arrays from the various configurations supported
x, y, u, v, c = _parse_args(*args, caller_name='barbs()')
x, y, u, v, c = _parse_args(*args, caller_name='barbs')
self.x = x
self.y = y
xy = np.column_stack((x, y))
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ def test_quiver_number_of_args():
X = [1, 2]
with pytest.raises(
TypeError,
match='takes 2-5 positional arguments but 1 were given'):
match='takes from 2 to 5 positional arguments but 1 were given'):
plt.quiver(X)
with pytest.raises(
TypeError,
match='takes 2-5 positional arguments but 6 were given'):
match='takes from 2 to 5 positional arguments but 6 were given'):
plt.quiver(X, X, X, X, X, X)


Expand Down