From dc875501400b45ce8eff19d6aad0884c7c7c8563 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Tue, 28 May 2019 01:03:06 -0400 Subject: [PATCH] Use cbook._check_in_list more often. --- lib/matplotlib/animation.py | 9 +++-- lib/matplotlib/axes/_axes.py | 39 +++++++++------------ lib/matplotlib/backends/backend_cairo.py | 16 ++++----- lib/matplotlib/collections.py | 12 +++---- lib/matplotlib/colorbar.py | 13 +++---- lib/matplotlib/image.py | 3 +- lib/matplotlib/legend.py | 7 ++-- lib/matplotlib/mlab.py | 15 +++----- lib/matplotlib/offsetbox.py | 8 ++--- lib/matplotlib/patches.py | 8 ++--- lib/matplotlib/scale.py | 3 +- lib/matplotlib/stackplot.py | 9 +++-- lib/matplotlib/streamplot.py | 8 ++--- lib/matplotlib/text.py | 6 ++-- lib/matplotlib/ticker.py | 8 ++--- lib/mpl_toolkits/axes_grid1/axes_divider.py | 8 ++--- lib/mpl_toolkits/axes_grid1/axes_size.py | 4 +-- lib/mpl_toolkits/axisartist/axislines.py | 4 +-- lib/mpl_toolkits/mplot3d/axes3d.py | 6 ++-- 19 files changed, 66 insertions(+), 120 deletions(-) diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index d4fc3fbe675d..0cfc773c4e04 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -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 diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 428daa1d77f4..70b78266b2f2 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -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, @@ -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'], @@ -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) @@ -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) @@ -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 @@ -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: @@ -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) diff --git a/lib/matplotlib/backends/backend_cairo.py b/lib/matplotlib/backends/backend_cairo.py index b567f8469262..9cfd5c7ad25e 100644 --- a/lib/matplotlib/backends/backend_cairo.py +++ b/lib/matplotlib/backends/backend_cairo.py @@ -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: @@ -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) diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index 08f449bc4858..2c01e24877af 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -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 @@ -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 diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index b2b212b7dbb0..fcd878ab515b 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -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. @@ -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), diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 84f4f1faf9a6..26f0c9475769 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -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 diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 3add9c39be5a..e2ec24e27750 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -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) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 7fd39af4e0f4..d8c523ba105b 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -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'") @@ -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: @@ -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) diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py index 53ca3d0d35fc..57c5c477b53b 100644 --- a/lib/matplotlib/offsetbox.py +++ b/lib/matplotlib/offsetbox.py @@ -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 diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 4c7306591e89..cff18c78ae2a 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -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 @@ -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 diff --git a/lib/matplotlib/scale.py b/lib/matplotlib/scale.py index 83086545bb2f..0499f6152e27 100644 --- a/lib/matplotlib/scale.py +++ b/lib/matplotlib/scale.py @@ -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__: diff --git a/lib/matplotlib/stackplot.py b/lib/matplotlib/stackplot.py index cb5a4daf6e5d..3ad1c1f4a91c 100644 --- a/lib/matplotlib/stackplot.py +++ b/lib/matplotlib/stackplot.py @@ -8,6 +8,8 @@ """ import numpy as np +import matplotlib.cbook as cbook + __all__ = ['stackplot'] @@ -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. @@ -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, :], diff --git a/lib/matplotlib/streamplot.py b/lib/matplotlib/streamplot.py index 215f3afbb017..2b2cbddb0732 100644 --- a/lib/matplotlib/streamplot.py +++ b/lib/matplotlib/streamplot.py @@ -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 @@ -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. diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index c054990b0368..3d9aec92a5ac 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -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): diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index 1fd873450abf..08122ce2259a 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -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')) @@ -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) diff --git a/lib/mpl_toolkits/axes_grid1/axes_divider.py b/lib/mpl_toolkits/axes_grid1/axes_divider.py index c6547d1e814f..370f7162e23c 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_divider.py +++ b/lib/mpl_toolkits/axes_grid1/axes_divider.py @@ -138,11 +138,9 @@ def set_anchor(self, anchor): ===== ============ """ - if anchor in mtransforms.Bbox.coefs or len(anchor) == 2: - self._anchor = anchor - else: - raise ValueError('argument must be among %s' % - ', '.join(mtransforms.BBox.coefs)) + if len(anchor) != 2: + cbook._check_in_list(mtransforms.Bbox.coefs, anchor=anchor) + self._anchor = anchor def get_anchor(self): "return the anchor" diff --git a/lib/mpl_toolkits/axes_grid1/axes_size.py b/lib/mpl_toolkits/axes_grid1/axes_size.py index 112843c95ce6..59568dd69c9e 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_size.py +++ b/lib/mpl_toolkits/axes_grid1/axes_size.py @@ -154,9 +154,7 @@ class MaxExtent(_Base): def __init__(self, artist_list, w_or_h): self._artist_list = artist_list - if w_or_h not in ["width", "height"]: - raise ValueError() - + cbook._check_in_list(["width", "height"], w_or_h=w_or_h) self._w_or_h = w_or_h def add_artist(self, a): diff --git a/lib/mpl_toolkits/axisartist/axislines.py b/lib/mpl_toolkits/axisartist/axislines.py index b954cc1466a0..e0d13ca2b3f3 100644 --- a/lib/mpl_toolkits/axisartist/axislines.py +++ b/lib/mpl_toolkits/axisartist/axislines.py @@ -121,11 +121,9 @@ def __init__(self, loc, nth_coord=None): nth_coord = along which coordinate value varies in 2d, nth_coord = 0 -> x axis, nth_coord = 1 -> y axis """ + cbook._check_in_list(["left", "right", "bottom", "top"], loc=loc) self._loc = loc - if loc not in ["left", "right", "bottom", "top"]: - raise ValueError("%s" % loc) - if nth_coord is None: if loc in ["left", "right"]: nth_coord = 1 diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index 5e57b328a79b..247040e5eea8 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -996,12 +996,11 @@ def set_proj_type(self, proj_type): Type of projection, accepts 'persp' and 'ortho'. """ + cbook._check_in_list(['persp', 'ortho'], proj_type=proj_type) if proj_type == 'persp': self._projection = proj3d.persp_transformation elif proj_type == 'ortho': self._projection = proj3d.ortho_transformation - else: - raise ValueError("unrecognized projection: %s" % proj_type) def get_proj(self): """ @@ -2694,12 +2693,11 @@ def calc_arrow(uvw, angle=15): shaft_dt = np.array([0, length]) arrow_dt = shaft_dt * arrow_length_ratio + cbook._check_in_list(['tail', 'middle', 'tip'], pivot=pivot) if pivot == 'tail': shaft_dt -= length elif pivot == 'middle': shaft_dt -= length/2. - elif pivot != 'tip': - raise ValueError('Invalid pivot argument: ' + str(pivot)) XYZ = np.column_stack(input_args[:3]) UVW = np.column_stack(input_args[3:argi]).astype(float)