Skip to content

Commit 2c22cc6

Browse files
authored
Merge pull request #14350 from QuLogic/check-in-list
MNT: Use cbook._check_in_list more often.
2 parents 9e9554e + dc87550 commit 2c22cc6

File tree

19 files changed

+66
-120
lines changed

19 files changed

+66
-120
lines changed

lib/matplotlib/animation.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -806,16 +806,15 @@ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
806806
# Convert from MB to bytes
807807
self._bytes_limit *= 1024 * 1024
808808

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

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

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

820819
self._saved_frames = []
821820
self._total_bytes = 0

lib/matplotlib/axes/_axes.py

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -138,12 +138,11 @@ def get_title(self, loc="center"):
138138
The title text string.
139139
140140
"""
141-
try:
142-
title = {'left': self._left_title,
143-
'center': self.title,
144-
'right': self._right_title}[loc.lower()]
145-
except KeyError:
146-
raise ValueError("'%s' is not a valid location" % loc)
141+
titles = {'left': self._left_title,
142+
'center': self.title,
143+
'right': self._right_title}
144+
cbook._check_in_list(titles, loc=loc.lower())
145+
title = titles[loc.lower()]
147146
return title.get_text()
148147

149148
def set_title(self, label, fontdict=None, loc=None, pad=None,
@@ -188,15 +187,14 @@ def set_title(self, label, fontdict=None, loc=None, pad=None,
188187
:class:`~matplotlib.text.Text` for a list of valid text
189188
properties.
190189
"""
191-
try:
192-
if loc is None:
193-
loc = rcParams['axes.titlelocation']
194-
195-
title = {'left': self._left_title,
196-
'center': self.title,
197-
'right': self._right_title}[loc.lower()]
198-
except KeyError:
199-
raise ValueError("'%s' is not a valid location" % loc)
190+
if loc is None:
191+
loc = rcParams['axes.titlelocation']
192+
193+
titles = {'left': self._left_title,
194+
'center': self.title,
195+
'right': self._right_title}
196+
cbook._check_in_list(titles, loc=loc.lower())
197+
title = titles[loc.lower()]
200198
default = {
201199
'fontsize': rcParams['axes.titlesize'],
202200
'fontweight': rcParams['axes.titleweight'],
@@ -2098,9 +2096,7 @@ def step(self, x, y, *args, where='pre', data=None, **kwargs):
20982096
-----
20992097
.. [notes section required to get data note injection right]
21002098
"""
2101-
if where not in ('pre', 'post', 'mid'):
2102-
raise ValueError("'where' argument to step must be "
2103-
"'pre', 'post' or 'mid'")
2099+
cbook._check_in_list(('pre', 'post', 'mid'), where=where)
21042100
kwargs['drawstyle'] = 'steps-' + where
21052101
return self.plot(x, y, *args, data=data, **kwargs)
21062102

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

22952291
orientation = kwargs.pop('orientation', 'vertical')
2292+
cbook._check_in_list(['vertical', 'horizontal'],
2293+
orientation=orientation)
22962294
log = kwargs.pop('log', False)
22972295
label = kwargs.pop('label', '')
22982296
tick_labels = kwargs.pop('tick_label', None)
@@ -2321,8 +2319,6 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
23212319
self._process_unit_info(xdata=width, ydata=y, kwargs=kwargs)
23222320
if log:
23232321
self.set_xscale('log', nonposx='clip')
2324-
else:
2325-
raise ValueError('invalid orientation: %s' % orientation)
23262322

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

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

23912386
patches = []
23922387
args = zip(left, bottom, width, height, color, edgecolor, linewidth)

lib/matplotlib/backends/backend_cairo.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -338,11 +338,9 @@ def set_alpha(self, alpha):
338338
# one for False.
339339

340340
def set_capstyle(self, cs):
341-
if cs in ('butt', 'round', 'projecting'):
342-
self._capstyle = cs
343-
self.ctx.set_line_cap(self._capd[cs])
344-
else:
345-
raise ValueError('Unrecognized cap style. Found %s' % cs)
341+
cbook._check_in_list(('butt', 'round', 'projecting'), capstyle=cs)
342+
self._capstyle = cs
343+
self.ctx.set_line_cap(self._capd[cs])
346344

347345
def set_clip_rectangle(self, rectangle):
348346
if not rectangle:
@@ -384,11 +382,9 @@ def get_rgb(self):
384382
return self.ctx.get_source().get_rgba()[:3]
385383

386384
def set_joinstyle(self, js):
387-
if js in ('miter', 'round', 'bevel'):
388-
self._joinstyle = js
389-
self.ctx.set_line_join(self._joind[js])
390-
else:
391-
raise ValueError('Unrecognized join style. Found %s' % js)
385+
cbook._check_in_list(('miter', 'round', 'bevel'), joinstyle=js)
386+
self._joinstyle = js
387+
self.ctx.set_line_join(self._joind[js])
392388

393389
def set_linewidth(self, w):
394390
self._linewidth = float(w)

lib/matplotlib/collections.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -559,10 +559,8 @@ def set_capstyle(self, cs):
559559
cs : {'butt', 'round', 'projecting'}
560560
The capstyle
561561
"""
562-
if cs in ('butt', 'round', 'projecting'):
563-
self._capstyle = cs
564-
else:
565-
raise ValueError('Unrecognized cap style. Found %s' % cs)
562+
cbook._check_in_list(('butt', 'round', 'projecting'), capstyle=cs)
563+
self._capstyle = cs
566564

567565
def get_capstyle(self):
568566
return self._capstyle
@@ -576,10 +574,8 @@ def set_joinstyle(self, js):
576574
js : {'miter', 'round', 'bevel'}
577575
The joinstyle
578576
"""
579-
if js in ('miter', 'round', 'bevel'):
580-
self._joinstyle = js
581-
else:
582-
raise ValueError('Unrecognized join style. Found %s' % js)
577+
cbook._check_in_list(('miter', 'round', 'bevel'), joinstyle=js)
578+
self._joinstyle = js
583579

584580
def get_joinstyle(self):
585581
return self._joinstyle

lib/matplotlib/colorbar.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -977,12 +977,9 @@ def _get_extension_lengths(self, frac, automin, automax, default=0.05):
977977
# Set the default value.
978978
extendlength = np.array([default, default])
979979
if isinstance(frac, str):
980-
if frac.lower() == 'auto':
981-
# Use the provided values when 'auto' is required.
982-
extendlength[:] = [automin, automax]
983-
else:
984-
# Any other string is invalid.
985-
raise ValueError('invalid value for extendfrac')
980+
cbook._check_in_list(['auto'], extendfrac=frac.lower())
981+
# Use the provided values when 'auto' is required.
982+
extendlength[:] = [automin, automax]
986983
elif frac is not None:
987984
try:
988985
# Try to set min and max extension fractions directly.
@@ -1351,9 +1348,7 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15,
13511348
if location is None:
13521349
location = 'right' if orientation == 'vertical' else 'bottom'
13531350

1354-
if location not in locations:
1355-
raise ValueError('Invalid colorbar location. Must be one '
1356-
'of %s' % ', '.join(locations))
1351+
cbook._check_in_list(locations, location=location)
13571352

13581353
default_location_settings = {'left': {'anchor': (1.0, 0.5),
13591354
'panchor': (0.0, 0.5),

lib/matplotlib/image.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -717,8 +717,7 @@ def set_interpolation(self, s):
717717
if s is None:
718718
s = rcParams['image.interpolation']
719719
s = s.lower()
720-
if s not in _interpd_:
721-
raise ValueError('Illegal interpolation string')
720+
cbook._check_in_list(_interpd_, interpolation=s)
722721
self._interpolation = s
723722
self.stale = True
724723

lib/matplotlib/legend.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,8 @@ def __init__(self, legend, use_blit=False, update="loc"):
6363
"""
6464
self.legend = legend
6565

66-
if update in ["loc", "bbox"]:
67-
self._update = update
68-
else:
69-
raise ValueError("update parameter '%s' is not supported." %
70-
update)
66+
cbook._check_in_list(["loc", "bbox"], update=update)
67+
self._update = update
7168

7269
DraggableOffsetBox.__init__(self, legend, legend._legend_box,
7370
use_blit=use_blit)

lib/matplotlib/mlab.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -466,10 +466,9 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
466466

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

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

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

611606
if pad_to is None:
612607
pad_to = len(x)

lib/matplotlib/offsetbox.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1019,12 +1019,8 @@ def __init__(self, loc,
10191019
self.set_child(child)
10201020

10211021
if isinstance(loc, str):
1022-
try:
1023-
loc = self.codes[loc]
1024-
except KeyError:
1025-
raise ValueError('Unrecognized location "%s". Valid '
1026-
'locations are\n\t%s\n'
1027-
% (loc, '\n\t'.join(self.codes)))
1022+
cbook._check_in_list(self.codes, loc=loc)
1023+
loc = self.codes[loc]
10281024

10291025
self.loc = loc
10301026
self.borderpad = borderpad

lib/matplotlib/patches.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -422,9 +422,7 @@ def set_capstyle(self, s):
422422
s : {'butt', 'round', 'projecting'}
423423
"""
424424
s = s.lower()
425-
if s not in self.validCap:
426-
raise ValueError('set_capstyle passed "%s";\n' % (s,) +
427-
'valid capstyles are %s' % (self.validCap,))
425+
cbook._check_in_list(self.validCap, capstyle=s)
428426
self._capstyle = s
429427
self.stale = True
430428

@@ -441,9 +439,7 @@ def set_joinstyle(self, s):
441439
s : {'miter', 'round', 'bevel'}
442440
"""
443441
s = s.lower()
444-
if s not in self.validJoin:
445-
raise ValueError('set_joinstyle passed "%s";\n' % (s,) +
446-
'valid joinstyles are %s' % (self.validJoin,))
442+
cbook._check_in_list(self.validJoin, joinstyle=s)
447443
self._joinstyle = s
448444
self.stale = True
449445

lib/matplotlib/scale.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -723,8 +723,7 @@ def scale_factory(scale, axis, **kwargs):
723723
axis : Axis
724724
"""
725725
scale = scale.lower()
726-
if scale not in _scale_mapping:
727-
raise ValueError("Unknown scale type '%s'" % scale)
726+
cbook._check_in_list(_scale_mapping, scale=scale)
728727
return _scale_mapping[scale](axis, **kwargs)
729728

730729
if scale_factory.__doc__:

lib/matplotlib/stackplot.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
"""
99
import numpy as np
1010

11+
import matplotlib.cbook as cbook
12+
1113
__all__ = ['stackplot']
1214

1315

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

73+
cbook._check_in_list(['zero', 'sym', 'wiggle', 'weighted_wiggle'],
74+
baseline=baseline)
7175
if baseline == 'zero':
7276
first_line = 0.
7377

@@ -97,11 +101,6 @@ def stackplot(axes, x, *args,
97101
first_line = center - 0.5 * total
98102
stack += first_line
99103

100-
else:
101-
errstr = "Baseline method %s not recognised. " % baseline
102-
errstr += "Expected 'zero', 'sym', 'wiggle' or 'weighted_wiggle'"
103-
raise ValueError(errstr)
104-
105104
# Color between x = 0 and the first array.
106105
color = axes._get_lines.get_next_color()
107106
coll = axes.fill_between(x, first_line, stack[0, :],

lib/matplotlib/streamplot.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import numpy as np
77

88
import matplotlib
9+
import matplotlib.cbook as cbook
910
import matplotlib.cm as cm
1011
import matplotlib.colors as mcolors
1112
import matplotlib.collections as mcollections
@@ -103,11 +104,8 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
103104
line_kw = {}
104105
arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)
105106

106-
if integration_direction not in ['both', 'forward', 'backward']:
107-
errstr = ("Integration direction '%s' not recognised. "
108-
"Expected 'both', 'forward' or 'backward'." %
109-
integration_direction)
110-
raise ValueError(errstr)
107+
cbook._check_in_list(['both', 'forward', 'backward'],
108+
integration_direction=integration_direction)
111109

112110
if integration_direction == 'both':
113111
maxlength /= 2.

lib/matplotlib/text.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -247,10 +247,8 @@ def set_rotation_mode(self, m):
247247
aligned according to their horizontal and vertical alignments. If
248248
``"anchor"``, then alignment occurs before rotation.
249249
"""
250-
if m is None or m in ["anchor", "default"]:
251-
self._rotation_mode = m
252-
else:
253-
raise ValueError("Unknown rotation_mode : %s" % repr(m))
250+
cbook._check_in_list(["anchor", "default", None], rotation_mode=m)
251+
self._rotation_mode = m
254252
self.stale = True
255253

256254
def get_rotation_mode(self):

lib/matplotlib/ticker.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1948,9 +1948,7 @@ def set_params(self, **kwargs):
19481948
self._symmetric = kwargs.pop('symmetric')
19491949
if 'prune' in kwargs:
19501950
prune = kwargs.pop('prune')
1951-
if prune is not None and prune not in ['upper', 'lower', 'both']:
1952-
raise ValueError(
1953-
"prune must be 'upper', 'lower', 'both', or None")
1951+
cbook._check_in_list(['upper', 'lower', 'both', None], prune=prune)
19541952
self._prune = prune
19551953
if 'min_n_ticks' in kwargs:
19561954
self._min_n_ticks = max(1, kwargs.pop('min_n_ticks'))
@@ -2206,9 +2204,7 @@ def subs(self, subs):
22062204
if subs is None: # consistency with previous bad API
22072205
self._subs = 'auto'
22082206
elif isinstance(subs, str):
2209-
if subs not in ('all', 'auto'):
2210-
raise ValueError("A subs string must be 'all' or 'auto'; "
2211-
"found '%s'." % subs)
2207+
cbook._check_in_list(('all', 'auto'), subs=subs)
22122208
self._subs = subs
22132209
else:
22142210
self._subs = np.asarray(subs, dtype=float)

0 commit comments

Comments
 (0)