8000 in _axes.py: Added repr to error messages instead of using str by Cloverwave · Pull Request #23383 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

in _axes.py: Added repr to error messages instead of using str #23383

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

Closed
wants to merge 2 commits into from
Closed
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
68 changes: 38 additions & 30 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -834,8 +834,8 @@ def _check_no_units(vals, names):
# Helper method to check that vals are not unitized
for val, name in zip(vals, names):
if not munits._is_natively_supported(val):
raise ValueError(f"{name} must be a single scalar value, "
f"but got {val}")
raise ValueError(f"{repr(name)} must be a single scalar value,"
f" but got {repr(val)}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
f" but got {repr(val)}")
f" but got {val!r}")

and so on also works (and is more compact).


@_docstring.dedent_interpd
def axline(self, xy1, xy2=None, *, slope=None, **kwargs):
Expand Down Expand Up @@ -2058,7 +2058,7 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,

if maxlags >= Nx or maxlags < 1:
raise ValueError('maxlags must be None or strictly '
'positive < %d' % Nx)
f'positive < {repr(Nx)}')

lags = np.arange(-maxlags, maxlags + 1)
correls = correls[Nx - 1 - maxlags:Nx + maxlags]
Expand Down Expand Up @@ -2402,9 +2402,10 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
try:
left = x - width / 2
except TypeError as e:
raise TypeError(f'the dtypes of parameters x ({x.dtype}) '
f'and width ({width.dtype}) '
f'are incompatible') from e
raise TypeError('the dtypes of parameters x'
f' ({repr(x.dtype)}) '
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure that we want repr here.

f'and width ({repr(width.dtype)}) '
'are incompatible') from e
bottom = y
else: # horizontal
try:
Expand Down Expand Up @@ -2899,7 +2900,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
"""
if not 1 <= len(args) <= 5:
raise TypeError('stem expected between 1 and 5 positional '
'arguments, got {}'.format(args))
f'arguments, got {repr(args)}')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will most likely not produce the expected results.

_api.check_in_list(['horizontal', 'vertical'], orientation=orientation)

if len(args) == 1:
Expand Down Expand Up @@ -3124,7 +3125,8 @@ def get_next_color():

_api.check_isinstance(Number, radius=radius, startangle=startangle)
if radius <= 0:
raise ValueError(f'radius must be a positive number, not {radius}')
raise ValueError('radius must be a positive number, not'
f' {repr(radius)}')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't make sense.


# Starting theta1 is the start fraction of the circle
theta1 = startangle / 360
Expand Down Expand Up @@ -3511,14 +3513,16 @@ def apply_mask(arrays, mask): return [array[mask] for array in arrays]
np.broadcast_to(err, (2, len(dep)))
except ValueError:
raise ValueError(
f"'{dep_axis}err' (shape: {np.shape(err)}) must be a "
f"scalar or a 1D or (2, n) array-like whose shape matches "
f"'{dep_axis}' (shape: {np.shape(dep)})") from None
f"'{repr(dep_axis)}err' (shape: {repr(np.shape(err))}) must"
" be a "
"scalar or a 1D or (2, n) array-like whose shape matches "
f"'{repr(dep_axis)}'"
f" (shape: {repr(np.shape(dep))})") from None
res = np.zeros(err.shape, dtype=bool) # Default in case of nan
if np.any(np.less(err, -err, out=res, where=(err == err))):
# like err<0, but also works for timedelta and nan.
raise ValueError(
f"'{dep_axis}err' must not contain negative values")
f"'{repr(dep_axis)}err' must not contain negative values")
# This is like
# elow, ehigh = np.broadcast_to(...)
# return dep - elow * ~lolims, dep + ehigh * ~uplims
Expand Down Expand Up @@ -4263,8 +4267,8 @@ def _parse_scatter_color_args(c, edgecolors, kwargs, xsize,

def invalid_shape_exception(csize, xsize):
return ValueError(
f"'c' argument has {csize} elements, which is inconsistent "
f"with 'x' and 'y' with size {xsize}.")
f"'c' argument has {repr(csize)} elements, which is"
f"inconsistent with 'x' and 'y' with size {repr(xsize)}.")

c_is_mapped = False # Unless proven otherwise below.
valid_shape = True # Unless proven otherwise below.
Expand Down Expand Up @@ -4308,8 +4312,8 @@ def invalid_shape_exception(csize, xsize):
# Both the mapping *and* the RGBA conversion failed: pretty
# severe failure => one may appreciate a verbose feedback.
raise ValueError(
f"'c' argument must be a color, a sequence of colors, "
f"or a sequence of numbers, not {c}") from err
"'c' argument must be a color, a sequence of colors, "
f"or a sequence of numbers, not {repr(c)}") from err
else:
if len(colors) not in (0, 1, xsize):
# NB: remember that a single color is also acceptable.
Expand Down Expand Up @@ -5188,8 +5192,9 @@ def _fill_between_x_or_y(
else:
where = np.asarray(where, dtype=bool)
if where.size != ind.size:
raise ValueError(f"where size ({where.size}) does not match "
f"{ind_dir} size ({ind.size})")
raise ValueError(f"where size ({repr(where.size)})"
" does not match "
f"{repr(ind_dir)} size ({repr(ind.size)})")
where = where & ~functools.reduce(
np.logical_or, map(np.ma.getmask, [ind, dep1, dep2]))

Expand Down Expand Up @@ -5570,8 +5575,8 @@ 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 TypeError(f'{repr(funcname)}() takes 1 or 3 positional'
f' arguments but {len(args)} were given')

Nx = X.shape[-1]
Ny = Y.shape[0]
Expand All @@ -5582,8 +5587,8 @@ def _pcolorargs(self, funcname, *args, shading='auto', **kwargs):
y = Y.reshape(Ny, 1)
Y = y.repeat(Nx, axis=1)
if X.shape != Y.shape:
raise TypeError(f'Incompatible X, Y inputs to {funcname}; '
f'see help({funcname})')
raise TypeError(f'Incompatible X, Y inputs to {repr(funcname)}; '
f'see help({repr(funcname)})')

if shading == 'auto':
if ncols == Nx and nrows == Ny:
Expand All @@ -5593,14 +5598,16 @@ def _pcolorargs(self, funcname, *args, shading='auto', **kwargs):

if shading == 'flat':
if (Nx, Ny) != (ncols + 1, nrows + 1):
raise TypeError('Dimensions of C %s are incompatible with'
' X (%d) and/or Y (%d); see help(%s)' % (
C.shape, Nx, Ny, funcname))
raise TypeError(f'Dimensions of C {repr(C.shape)} are'
' incompatible with'
f' X ({repr(Nx)}) and/or Y ({repr(Ny)});'
' see help({repr(funcname)})')
else: # ['nearest', 'gouraud']:
if (Nx, Ny) != (ncols, nrows):
raise TypeError('Dimensions of C %s are incompatible with'
' X (%d) and/or Y (%d); see help(%s)' % (
C.shape, Nx, Ny, funcname))
raise TypeError(f'Dimensions of C {repr(C.shape)}'
' are incompatible with'
f' X ({repr(Nx)}) and/or Y ({repr(Ny)});'
' see help({repr(funcname)})')
if shading == 'nearest':
# grid is specified at the center, so define corners
# at the midpoints between the grid centers and then use the
Expand Down Expand Up @@ -6617,8 +6624,9 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
color = mcolors.to_rgba_array(color)
if len(color) != nx:
raise ValueError(f"The 'color' keyword argument must have one "
f"color per dataset, but {nx} datasets and "
f"{len(color)} colors were provided")
f"color per dataset, but {repr(nx)}"
" datasets and "
f"{repr(len(color))} colors were provided")

hist_kwargs = dict()

Expand Down
0