Skip to content

Use cbook._check_in_list more often. #14350

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
May 28, 2019
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
9 changes: 4 additions & 5 deletions lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,16 +806,15 @@ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
# Convert from MB to bytes
self._bytes_limit *= 1024 * 1024

if self.default_mode not in ['loop', 'once', 'reflect']:
raise ValueError(
"unrecognized default_mode {!r}".format(self.default_mode))
cbook._check_in_list(['loop', 'once', 'reflect'],
default_mode=self.default_mode)

super().__init__(fps, codec, bitrate, extra_args, metadata)

def setup(self, fig, outfile, dpi, frame_dir=None):
outfile = Path(outfile)
if outfile.suffix not in ['.html', '.htm']:
raise ValueError("outfile must be *.htm or *.html")
cbook._check_in_list(['.html', '.htm'],
outfile_extension=outfile.suffix)

self._saved_frames = []
self._total_bytes = 0
Expand Down
39 changes: 17 additions & 22 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,11 @@ def get_title(self, loc="center"):
The title text string.

"""
try:
title = {'left': self._left_title,
'center': self.title,
'right': self._right_title}[loc.lower()]
except KeyError:
raise ValueError("'%s' is not a valid location" % loc)
titles = {'left': self._left_title,
'center': self.title,
'right': self._right_title}
cbook._check_in_list(titles, loc=loc.lower())
title = titles[loc.lower()]
return title.get_text()

def set_title(self, label, fontdict=None, loc=None, pad=None,
Expand Down Expand Up @@ -188,15 +187,14 @@ def set_title(self, label, fontdict=None, loc=None, pad=None,
:class:`~matplotlib.text.Text` for a list of valid text
properties.
"""
try:
if loc is None:
loc = rcParams['axes.titlelocation']

title = {'left': self._left_title,
'center': self.title,
'right': self._right_title}[loc.lower()]
except KeyError:
raise ValueError("'%s' is not a valid location" % loc)
if loc is None:
loc = rcParams['axes.titlelocation']

titles = {'left': self._left_title,
'center': self.title,
'right': self._right_title}
cbook._check_in_list(titles, loc=loc.lower())
title = titles[loc.lower()]
default = {
'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
Expand Down Expand Up @@ -2098,9 +2096,7 @@ def step(self, x, y, *args, where='pre', data=None, **kwargs):
-----
.. [notes section required to get data note injection right]
"""
if where not in ('pre', 'post', 'mid'):
raise ValueError("'where' argument to step must be "
"'pre', 'post' or 'mid'")
cbook._check_in_list(('pre', 'post', 'mid'), where=where)
kwargs['drawstyle'] = 'steps-' + where
return self.plot(x, y, *args, data=data, **kwargs)

Expand Down Expand Up @@ -2293,6 +2289,8 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
error_kw.setdefault('capsize', capsize)

orientation = kwargs.pop('orientation', 'vertical')
cbook._check_in_list(['vertical', 'horizontal'],
orientation=orientation)
log = kwargs.pop('log', False)
label = kwargs.pop('label', '')
tick_labels = kwargs.pop('tick_label', None)
Expand Down Expand Up @@ -2321,8 +2319,6 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
self._process_unit_info(xdata=width, ydata=y, kwargs=kwargs)
if log:
self.set_xscale('log', nonposx='clip')
else:
raise ValueError('invalid orientation: %s' % orientation)

# lets do some conversions now since some types cannot be
# subtracted uniformly
Expand Down Expand Up @@ -2365,6 +2361,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",

# We will now resolve the alignment and really have
# left, bottom, width, height vectors
cbook._check_in_list(['center', 'edge'], align=align)
if align == 'center':
if orientation == 'vertical':
try:
Expand All @@ -2385,8 +2382,6 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
elif align == 'edge':
left = x
bottom = y
else:
raise ValueError('invalid alignment: %s' % align)

patches = []
args = zip(left, bottom, width, height, color, edgecolor, linewidth)
Expand Down
16 changes: 6 additions & 10 deletions lib/matplotlib/backends/backend_cairo.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,9 @@ def set_alpha(self, alpha):
# one for False.

def set_capstyle(self, cs):
if cs in ('butt', 'round', 'projecting'):
self._capstyle = cs
self.ctx.set_line_cap(self._capd[cs])
else:
raise ValueError('Unrecognized cap style. Found %s' % cs)
cbook._check_in_list(('butt', 'round', 'projecting'), capstyle=cs)
self._capstyle = cs
self.ctx.set_line_cap(self._capd[cs])

def set_clip_rectangle(self, rectangle):
if not rectangle:
Expand Down Expand Up @@ -384,11 +382,9 @@ def get_rgb(self):
return self.ctx.get_source().get_rgba()[:3]

def set_joinstyle(self, js):
if js in ('miter', 'round', 'bevel'):
self._joinstyle = js
self.ctx.set_line_join(self._joind[js])
else:
raise ValueError('Unrecognized join style. Found %s' % js)
cbook._check_in_list(('miter', 'round', 'bevel'), joinstyle=js)
self._joinstyle = js
self.ctx.set_line_join(self._joind[js])

def set_linewidth(self, w):
self._linewidth = float(w)
Expand Down
12 changes: 4 additions & 8 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,10 +559,8 @@ def set_capstyle(self, cs):
cs : {'butt', 'round', 'projecting'}
The capstyle
"""
if cs in ('butt', 'round', 'projecting'):
self._capstyle = cs
else:
raise ValueError('Unrecognized cap style. Found %s' % cs)
cbook._check_in_list(('butt', 'round', 'projecting'), capstyle=cs)
self._capstyle = cs

def get_capstyle(self):
return self._capstyle
Expand All @@ -576,10 +574,8 @@ def set_joinstyle(self, js):
js : {'miter', 'round', 'bevel'}
The joinstyle
"""
if js in ('miter', 'round', 'bevel'):
self._joinstyle = js
else:
raise ValueError('Unrecognized join style. Found %s' % js)
cbook._check_in_list(('miter', 'round', 'bevel'), joinstyle=js)
self._joinstyle = js

def get_joinstyle(self):
return self._joinstyle
Expand Down
13 changes: 4 additions & 9 deletions lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -977,12 +977,9 @@ def _get_extension_lengths(self, frac, automin, automax, default=0.05):
# Set the default value.
extendlength = np.array([default, default])
if isinstance(frac, str):
if frac.lower() == 'auto':
# Use the provided values when 'auto' is required.
extendlength[:] = [automin, automax]
else:
# Any other string is invalid.
raise ValueError('invalid value for extendfrac')
cbook._check_in_list(['auto'], extendfrac=frac.lower())
# Use the provided values when 'auto' is required.
extendlength[:] = [automin, automax]
elif frac is not None:
try:
# Try to set min and max extension fractions directly.
Expand Down Expand Up @@ -1351,9 +1348,7 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15,
if location is None:
location = 'right' if orientation == 'vertical' else 'bottom'

if location not in locations:
raise ValueError('Invalid colorbar location. Must be one '
'of %s' % ', '.join(locations))
cbook._check_in_list(locations, location=location)

default_location_settings = {'left': {'anchor': (1.0, 0.5),
'panchor': (0.0, 0.5),
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,8 +717,7 @@ def set_interpolation(self, s):
if s is None:
s = rcParams['image.interpolation']
s = s.lower()
if s not in _interpd_:
raise ValueError('Illegal interpolation string')
cbook._check_in_list(_interpd_, interpolation=s)
self._interpolation = s
self.stale = True

Expand Down
7 changes: 2 additions & 5 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,8 @@ def __init__(self, legend, use_blit=False, update="loc"):
"""
self.legend = legend

if update in ["loc", "bbox"]:
self._update = update
else:
raise ValueError("update parameter '%s' is not supported." %
update)
cbook._check_in_list(["loc", "bbox"], update=update)
self._update = update

DraggableOffsetBox.__init__(self, legend, legend._legend_box,
use_blit=use_blit)
Expand Down
15 changes: 5 additions & 10 deletions lib/matplotlib/mlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,10 +466,9 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,

if mode is None or mode == 'default':
mode = 'psd'
elif mode not in ['psd', 'complex', 'magnitude', 'angle', 'phase']:
raise ValueError("Unknown value for mode %s, must be one of: "
"'default', 'psd', 'complex', "
"'magnitude', 'angle', 'phase'" % mode)
cbook._check_in_list(
['default', 'psd', 'complex', 'magnitude', 'angle', 'phase'],
mode=mode)

if not same_data and mode != 'psd':
raise ValueError("x and y must be equal if mode is not 'psd'")
Expand All @@ -485,9 +484,7 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
sides = 'twosided'
else:
sides = 'onesided'
elif sides not in ['onesided', 'twosided']:
raise ValueError("Unknown value for sides %s, must be one of: "
"'default', 'onesided', or 'twosided'" % sides)
cbook._check_in_list(['default', 'onesided', 'twosided'], sides=sides)

# zero pad x and y up to NFFT if they are shorter than NFFT
if len(x) < NFFT:
Expand Down Expand Up @@ -604,9 +601,7 @@ def _single_spectrum_helper(x, mode, Fs=None, window=None, pad_to=None,
complex, magnitude, angle, and phase spectrums.
It is *NOT* meant to be used outside of mlab and may change at any time.
'''
if mode is None or mode == 'psd' or mode == 'default':
raise ValueError('_single_spectrum_helper does not work with %s mode'
% mode)
cbook._check_in_list(['complex', 'magnitude', 'angle', 'phase'], mode=mode)

if pad_to is None:
pad_to = len(x)
Expand Down
8 changes: 2 additions & 6 deletions lib/matplotlib/offsetbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -1019,12 +1019,8 @@ def __init__(self, loc,
self.set_child(child)

if isinstance(loc, str):
try:
loc = self.codes[loc]
except KeyError:
raise ValueError('Unrecognized location "%s". Valid '
'locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes)))
cbook._check_in_list(self.codes, loc=loc)
loc = self.codes[loc]

self.loc = loc
self.borderpad = borderpad
Expand Down
8 changes: 2 additions & 6 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,9 +422,7 @@ def set_capstyle(self, s):
s : {'butt', 'round', 'projecting'}
"""
s = s.lower()
if s not in self.validCap:
raise ValueError('set_capstyle passed "%s";\n' % (s,) +
'valid capstyles are %s' % (self.validCap,))
cbook._check_in_list(self.validCap, capstyle=s)
self._capstyle = s
self.stale = True

Expand All @@ -441,9 +439,7 @@ def set_joinstyle(self, s):
s : {'miter', 'round', 'bevel'}
"""
s = s.lower()
if s not in self.validJoin:
raise ValueError('set_joinstyle passed "%s";\n' % (s,) +
'valid joinstyles are %s' % (self.validJoin,))
cbook._check_in_list(self.validJoin, joinstyle=s)
self._joinstyle = s
self.stale = True

Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,8 +723,7 @@ def scale_factory(scale, axis, **kwargs):
axis : Axis
"""
scale = scale.lower()
if scale not in _scale_mapping:
raise ValueError("Unknown scale type '%s'" % scale)
cbook._check_in_list(_scale_mapping, scale=scale)
return _scale_mapping[scale](axis, **kwargs)

if scale_factory.__doc__:
Expand Down
9 changes: 4 additions & 5 deletions lib/matplotlib/stackplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"""
import numpy as np

import matplotlib.cbook as cbook

__all__ = ['stackplot']


Expand Down Expand Up @@ -68,6 +70,8 @@ def stackplot(axes, x, *args,
# We'll need a float buffer for the upcoming calculations.
stack = np.cumsum(y, axis=0, dtype=np.promote_types(y.dtype, np.float32))

cbook._check_in_list(['zero', 'sym', 'wiggle', 'weighted_wiggle'],
baseline=baseline)
if baseline == 'zero':
first_line = 0.

Expand Down Expand Up @@ -97,11 +101,6 @@ def stackplot(axes, x, *args,
first_line = center - 0.5 * total
stack += first_line

else:
errstr = "Baseline method %s not recognised. " % baseline
errstr += "Expected 'zero', 'sym', 'wiggle' or 'weighted_wiggle'"
raise ValueError(errstr)

# Color between x = 0 and the first array.
color = axes._get_lines.get_next_color()
coll = axes.fill_between(x, first_line, stack[0, :],
Expand Down
8 changes: 3 additions & 5 deletions lib/matplotlib/streamplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import numpy as np

import matplotlib
import matplotlib.cbook as cbook
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import matplotlib.collections as mcollections
Expand Down Expand Up @@ -103,11 +104,8 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
line_kw = {}
arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)

if integration_direction not in ['both', 'forward', 'backward']:
errstr = ("Integration direction '%s' not recognised. "
"Expected 'both', 'forward' or 'backward'." %
integration_direction)
raise ValueError(errstr)
cbook._check_in_list(['both', 'forward', 'backward'],
integration_direction=integration_direction)

if integration_direction == 'both':
maxlength /= 2.
Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,8 @@ def set_rotation_mode(self, m):
aligned according to their horizontal and vertical alignments. If
``"anchor"``, then alignment occurs before rotation.
"""
if m is None or m in ["anchor", "default"]:
self._rotation_mode = m
else:
raise ValueError("Unknown rotation_mode : %s" % repr(m))
cbook._check_in_list(["anchor", "default", None], rotation_mode=m)
self._rotation_mode = m
self.stale = True

def get_rotation_mode(self):
Expand Down
8 changes: 2 additions & 6 deletions lib/matplotlib/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1948,9 +1948,7 @@ def set_params(self, **kwargs):
self._symmetric = kwargs.pop('symmetric')
if 'prune' in kwargs:
prune = kwargs.pop('prune')
if prune is not None and prune not in ['upper', 'lower', 'both']:
raise ValueError(
"prune must be 'upper', 'lower', 'both', or None")
cbook._check_in_list(['upper', 'lower', 'both', None], prune=prune)
self._prune = prune
if 'min_n_ticks' in kwargs:
self._min_n_ticks = max(1, kwargs.pop('min_n_ticks'))
Expand Down Expand Up @@ -2206,9 +2204,7 @@ def subs(self, subs):
if subs is None: # consistency with previous bad API
self._subs = 'auto'
elif isinstance(subs, str):
if subs not in ('all', 'auto'):
raise ValueError("A subs string must be 'all' or 'auto'; "
"found '%s'." % subs)
cbook._check_in_list(('all', 'auto'), subs=subs)
self._subs = subs
else:
self._subs = np.asarray(subs, dtype=float)
Expand Down
Loading