From c0f839bf9b332c410f393ed330271fbcf8128f40 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sun, 23 Sep 2018 16:05:10 +0200 Subject: [PATCH] Add helper function to check that an argument is in a list of strings. --- doc/api/next_api_changes/2019-01-22-AL.rst | 5 ++ lib/matplotlib/axes/_base.py | 10 ++-- lib/matplotlib/axes/_subplots.py | 2 +- lib/matplotlib/axis.py | 11 ++-- lib/matplotlib/backends/backend_ps.py | 9 ++-- .../backends/backend_webagg_core.py | 6 +-- lib/matplotlib/cbook/__init__.py | 22 ++++++++ lib/matplotlib/collections.py | 11 ++-- lib/matplotlib/contour.py | 4 +- lib/matplotlib/figure.py | 28 ++++------ lib/matplotlib/font_manager.py | 6 +-- lib/matplotlib/lines.py | 28 +++------- lib/matplotlib/mathtext.py | 12 ++--- lib/matplotlib/projections/geo.py | 10 ++-- lib/matplotlib/projections/polar.py | 14 +++-- lib/matplotlib/quiver.py | 5 +- lib/matplotlib/scale.py | 8 ++- lib/matplotlib/text.py | 21 +++----- lib/matplotlib/tri/tripcolor.py | 5 +- lib/matplotlib/widgets.py | 12 ++--- lib/mpl_toolkits/axes_grid1/axes_divider.py | 11 ++-- lib/mpl_toolkits/axes_grid1/axes_size.py | 6 +-- lib/mpl_toolkits/axes_grid1/parasite_axes.py | 10 ++-- lib/mpl_toolkits/axisartist/axis_artist.py | 53 +++++-------------- lib/mpl_toolkits/mplot3d/axes3d.py | 3 +- 25 files changed, 121 insertions(+), 191 deletions(-) create mode 100644 doc/api/next_api_changes/2019-01-22-AL.rst diff --git a/doc/api/next_api_changes/2019-01-22-AL.rst b/doc/api/next_api_changes/2019-01-22-AL.rst new file mode 100644 index 000000000000..5ba6747a087c --- /dev/null +++ b/doc/api/next_api_changes/2019-01-22-AL.rst @@ -0,0 +1,5 @@ +Changed exceptions +`````````````````` + +- `mpl_toolkits.axes_grid1.axes_size.GetExtentHelper` now raises `ValueError` + for invalid directions instead of `KeyError`. diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 5fde8bf01539..c2b48b9d9e1b 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -1328,8 +1328,7 @@ def set_adjustable(self, adjustable, share=False): which the adjustments for aspect ratios are done sequentially and independently on each Axes as it is drawn. """ - if adjustable not in ('box', 'datalim'): - raise ValueError("argument must be 'box', or 'datalim'") + cbook._check_in_list(["box", "datalim"], adjustable=adjustable) if share: axes = set(self._shared_x_axes.get_siblings(self) + self._shared_y_axes.get_siblings(self)) @@ -2745,9 +2744,7 @@ def grid(self, b=None, which='major', axis='both', **kwargs): """ if len(kwargs): b = True - if axis not in ['x', 'y', 'both']: - raise ValueError("The argument 'axis' must be one of 'x', 'y' or " - "'both'.") + cbook._check_in_list(['x', 'y', 'both'], axis=axis) if axis in ['x', 'both']: self.xaxis.grid(b, which=which, **kwargs) if axis in ['y', 'both']: @@ -2963,8 +2960,7 @@ def tick_params(self, axis='both', **kwargs): also be red. Gridlines will be red and translucent. """ - if axis not in ['x', 'y', 'both']: - raise ValueError("axis must be one of 'x', 'y' or 'both'") + cbook._check_in_list(['x', 'y', 'both'], axis=axis) if axis in ['x', 'both']: xkw = dict(kwargs) xkw.pop('left', None) diff --git a/lib/matplotlib/axes/_subplots.py b/lib/matplotlib/axes/_subplots.py index 5becb1aae371..001f5f1624cb 100644 --- a/lib/matplotlib/axes/_subplots.py +++ b/lib/matplotlib/axes/_subplots.py @@ -1,7 +1,7 @@ import functools import uuid -from matplotlib import docstring +from matplotlib import cbook, docstring import matplotlib.artist as martist from matplotlib.axes._axes import Axes from matplotlib.gridspec import GridSpec, SubplotSpec diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index cc5e2d6bd187..fd3ee314dad0 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -204,9 +204,7 @@ def _set_labelrotation(self, labelrotation): else: mode = 'default' angle = labelrotation - if mode not in ('auto', 'default'): - raise ValueError("Label rotation mode must be 'default' or " - "'auto', not '{}'.".format(mode)) + cbook._check_in_list(['auto', 'default'], labelrotation=mode) self._labelrotation = (mode, angle) def apply_tickdir(self, tickdir): @@ -1269,8 +1267,7 @@ def get_ticklabels(self, minor=False, which=None): elif which == 'both': return self.get_majorticklabels() + self.get_minorticklabels() else: - raise ValueError("`which` must be one of ('minor', 'major', " - "'both') not " + str(which)) + cbook._check_in_list(['major', 'minor', 'both'], which=which) if minor: return self.get_minorticklabels() return self.get_majorticklabels() @@ -1426,9 +1423,7 @@ def grid(self, b=None, which='major', **kwargs): 'grid will be enabled.') b = True which = which.lower() - if which not in ['major', 'minor', 'both']: - raise ValueError("The argument 'which' must be one of 'major', " - "'minor' or 'both'.") + cbook._check_in_list(['major', 'minor', 'both'], which=which) gridkw = {'grid_' + item[0]: item[1] for item in kwargs.items()} if which in ['minor', 'both']: diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index 2b4f3233c0e4..529bed5f41c1 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -838,12 +838,9 @@ def _print_ps(self, outfile, format, *args, (papertype, ', '.join(papersize))) orientation = orientation.lower() - if orientation == 'landscape': - isLandscape = True - elif orientation == 'portrait': - isLandscape = False - else: - raise RuntimeError('Orientation must be "portrait" or "landscape"') + cbook._check_in_list(['landscape', 'portrait'], + orientation=orientation) + isLandscape = (orientation == 'landscape') self.figure.set_dpi(72) # Override the dpi kwarg diff --git a/lib/matplotlib/backends/backend_webagg_core.py b/lib/matplotlib/backends/backend_webagg_core.py index 16ca41d7fdd4..72bd66f9e066 100644 --- a/lib/matplotlib/backends/backend_webagg_core.py +++ b/lib/matplotlib/backends/backend_webagg_core.py @@ -20,9 +20,9 @@ import numpy as np import tornado +from matplotlib import backend_bases, cbook, _png from matplotlib.backends import backend_agg from matplotlib.backend_bases import _Backend -from matplotlib import backend_bases, _png _log = logging.getLogger(__name__) @@ -163,10 +163,8 @@ def set_image_mode(self, mode): Note: diff images may not contain transparency, therefore upon draw this mode may be changed if the resulting image has any transparent component. - """ - if mode not in ['full', 'diff']: - raise ValueError('image mode must be either full or diff.') + cbook._check_in_list(['full', 'diff'], mode=mode) if self._current_image_mode != mode: self._current_image_mode = mode self.handle_send_image_mode(None) diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 24ae18d1a143..e935ceed2bad 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -2111,6 +2111,12 @@ def _unmultiplied_rgba8888_to_premultiplied_argb32(rgba8888): def _check_and_log_subprocess(command, logger, **kwargs): + """ + Run *command* using `subprocess.check_output`. If it succeeds, return the + output (stdout and stderr); if not, raise an exception whose text includes + the failed command and captured output. Both the command and the output + are logged at DEBUG level on *logger*. + """ logger.debug(command) try: report = subprocess.check_output( @@ -2134,3 +2140,19 @@ def _check_not_matrix(**kwargs): for k, v in kwargs.items(): if isinstance(v, np.matrix): raise TypeError(f"Argument {k!r} cannot be a np.matrix") + + +def _check_in_list(values, **kwargs): + """ + For each *key, value* pair in *kwargs*, check that *value* is in *values*; + if not, raise an appropriate ValueError. + + Examples + -------- + >>> cbook._check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg) + """ + for k, v in kwargs.items(): + if v not in values: + raise ValueError( + "{!r} is not a valid value for {}; supported values are {}" + .format(v, k, ', '.join(map(repr, values)))) diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index af6f8ed12a98..3a460efd878b 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -464,8 +464,8 @@ def set_offset_position(self, offset_position): ---------- offset_position : {'screen', 'data'} """ - if offset_position not in ('screen', 'data'): - raise ValueError("offset_position must be 'screen' or 'data'") + cbook._check_in_list(['screen', 'data'], + offset_position=offset_position) self._offset_position = offset_position self.stale = True @@ -1490,7 +1490,8 @@ def __init__(self, coord1 in positions] self._is_horizontal = False else: - raise ValueError("orientation must be 'horizontal' or 'vertical'") + cbook._check_in_list(['horizontal', 'vertical'], + orientation=orientation) LineCollection.__init__(self, segments, @@ -1583,8 +1584,8 @@ def set_orientation(self, orientation=None): elif orientation.lower() == 'vertical': is_horizontal = False else: - raise ValueError("orientation must be 'horizontal' or 'vertical'") - + cbook._check_in_list(['horizontal', 'vertical'], + orientation=orientation) if is_horizontal == self.is_horizontal(): return self.switch_orientation() diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index 22bd15749cbf..f874d2e63d45 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -842,9 +842,7 @@ def __init__(self, ax, *args, else: self.logscale = False - if self.origin not in [None, 'lower', 'upper', 'image']: - raise ValueError("If given, *origin* must be one of [ 'lower' |" - " 'upper' | 'image']") + cbook._check_in_list([None, 'lower', 'upper', 'image'], origin=origin) if self.extent is not None and len(self.extent) != 4: raise ValueError("If given, *extent* must be '[ *None* |" " (x0,x1,y0,y1) ]'") diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 0872f10247e8..a1ffa1a86e66 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -1524,23 +1524,17 @@ def subplots(self, nrows=1, ncols=1, sharex=False, sharey=False, sharex = "all" if sharex else "none" if isinstance(sharey, bool): sharey = "all" if sharey else "none" - share_values = ["all", "row", "col", "none"] - if sharex not in share_values: - # This check was added because it is very easy to type - # `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended. - # In most cases, no error will ever occur, but mysterious behavior - # will result because what was intended to be the subplot index is - # instead treated as a bool for sharex. - if isinstance(sharex, Integral): - cbook._warn_external("sharex argument to subplots() was an " - "integer. Did you intend to use " - "subplot() (without 's')?") - - raise ValueError("sharex [%s] must be one of %s" % - (sharex, share_values)) - if sharey not in share_values: - raise ValueError("sharey [%s] must be one of %s" % - (sharey, share_values)) + # This check was added because it is very easy to type + # `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended. + # In most cases, no error will ever occur, but mysterious behavior + # will result because what was intended to be the subplot index is + # instead treated as a bool for sharex. + if isinstance(sharex, Integral): + cbook._warn_external( + "sharex argument to subplots() was an integer. Did you " + "intend to use subplot() (without 's')?") + cbook._check_in_list(["all", "row", "col", "none"], + sharex=sharex, sharey=sharey) if subplot_kw is None: subplot_kw = {} if gridspec_kw is None: diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index 5e3ea26b278f..a1a687fa5934 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -759,8 +759,7 @@ def set_style(self, style): """ if style is None: style = rcParams['font.style'] - if style not in ('normal', 'italic', 'oblique'): - raise ValueError("style must be normal, italic or oblique") + cbook._check_in_list(['normal', 'italic', 'oblique'], style=style) self._slant = style set_slant = set_style @@ -770,8 +769,7 @@ def set_variant(self, variant): """ if variant is None: variant = rcParams['font.variant'] - if variant not in ('normal', 'small-caps'): - raise ValueError("variant must be normal or small-caps") + cbook._check_in_list(['normal', 'small-caps'], variant=variant) self._variant = variant def set_weight(self, weight): diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index 7288330c5ce9..aafb56ac2415 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -1083,8 +1083,7 @@ def set_drawstyle(self, drawstyle): """ if drawstyle is None: drawstyle = 'default' - if drawstyle not in self.drawStyles: - raise ValueError('Unrecognized drawstyle {!r}'.format(drawstyle)) + cbook._check_in_list(self.drawStyles, drawstyle=drawstyle) if self._drawstyle != drawstyle: self.stale = True # invalidate to trigger a recache of the path @@ -1181,13 +1180,9 @@ def set_linestyle(self, ls): if ls in [' ', '', 'none']: ls = 'None' + cbook._check_in_list([*self._lineStyles, *ls_mapper_r], ls=ls) if ls not in self._lineStyles: - try: - ls = ls_mapper_r[ls] - except KeyError: - raise ValueError("Invalid linestyle {!r}; see docs of " - "Line2D.set_linestyle for valid values" - .format(ls)) + ls = ls_mapper_r[ls] self._linestyle = ls else: self._linestyle = '--' @@ -1362,9 +1357,7 @@ def set_dash_joinstyle(self, s): For examples see :doc:`/gallery/lines_bars_and_markers/joinstyle`. """ s = s.lower() - if s not in self.validJoin: - raise ValueError('set_dash_joinstyle passed "%s";\n' % (s,) - + 'valid joinstyles are %s' % (self.validJoin,)) + cbook._check_in_list(self.validJoin, s=s) if self._dashjoinstyle != s: self.stale = True self._dashjoinstyle = s @@ -1379,10 +1372,7 @@ def set_solid_joinstyle(self, s): For examples see :doc:`/gallery/lines_bars_and_markers/joinstyle`. """ s = s.lower() - if s not in self.validJoin: - raise ValueError('set_solid_joinstyle passed "%s";\n' % (s,) - + 'valid joinstyles are %s' % (self.validJoin,)) - + cbook._check_in_list(self.validJoin, s=s) if self._solidjoinstyle != s: self.stale = True self._solidjoinstyle = s @@ -1412,9 +1402,7 @@ def set_dash_capstyle(self, s): s : {'butt', 'round', 'projecting'} """ s = s.lower() - if s not in self.validCap: - raise ValueError('set_dash_capstyle passed "%s";\n' % (s,) - + 'valid capstyles are %s' % (self.validCap,)) + cbook._check_in_list(self.validCap, s=s) if self._dashcapstyle != s: self.stale = True self._dashcapstyle = s @@ -1428,9 +1416,7 @@ def set_solid_capstyle(self, s): s : {'butt', 'round', 'projecting'} """ s = s.lower() - if s not in self.validCap: - raise ValueError('set_solid_capstyle passed "%s";\n' % (s,) - + 'valid capstyles are %s' % (self.validCap,)) + cbook._check_in_list(self.validCap, s=s) if self._solidcapstyle != s: self.stale = True self._solidcapstyle = s diff --git a/lib/matplotlib/mathtext.py b/lib/matplotlib/mathtext.py index 6d83d9d8a330..62a2107e0f93 100644 --- a/lib/matplotlib/mathtext.py +++ b/lib/matplotlib/mathtext.py @@ -3351,14 +3351,10 @@ def parse(self, s, dpi = 72, prop = None): font_output = StandardPsFonts(prop) else: backend = self._backend_mapping[self._output]() - fontset = rcParams['mathtext.fontset'] - fontset_class = self._font_type_mapping.get(fontset.lower()) - if fontset_class is not None: - font_output = fontset_class(prop, backend) - else: - raise ValueError( - "mathtext.fontset must be either 'cm', 'dejavuserif', " - "'dejavusans', 'stix', 'stixsans', or 'custom'") + fontset = rcParams['mathtext.fontset'].lower() + cbook._check_in_list(self._font_type_mapping, fontset=fontset) + fontset_class = self._font_type_mapping[fontset] + font_output = fontset_class(prop, backend) fontsize = prop.get_size_in_points() diff --git a/lib/matplotlib/projections/geo.py b/lib/matplotlib/projections/geo.py index cc4e24376bba..7d1a96c91d21 100644 --- a/lib/matplotlib/projections/geo.py +++ b/lib/matplotlib/projections/geo.py @@ -1,6 +1,6 @@ import numpy as np -from matplotlib import rcParams +from matplotlib import cbook, rcParams from matplotlib.axes import Axes import matplotlib.axis as maxis from matplotlib.patches import Circle @@ -118,9 +118,7 @@ def _get_affine_transform(self): .translate(0.5, 0.5) def get_xaxis_transform(self, which='grid'): - if which not in ['tick1', 'tick2', 'grid']: - raise ValueError( - "'which' must be one of 'tick1', 'tick2', or 'grid'") + cbook._check_in_list(['tick1', 'tick2', 'grid'], which=which) return self._xaxis_transform def get_xaxis_text1_transform(self, pad): @@ -130,9 +128,7 @@ def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'top', 'center' def get_yaxis_transform(self, which='grid'): - if which not in ['tick1', 'tick2', 'grid']: - raise ValueError( - "'which' must be one of 'tick1', 'tick2', or 'grid'") + cbook._check_in_list(['tick1', 'tick2', 'grid'], which=which) return self._yaxis_transform def get_yaxis_text1_transform(self, pad): diff --git a/lib/matplotlib/projections/polar.py b/lib/matplotlib/projections/polar.py index 59f2bc83a4a6..e32ed5b79d72 100644 --- a/lib/matplotlib/projections/polar.py +++ b/lib/matplotlib/projections/polar.py @@ -3,12 +3,12 @@ import numpy as np +from matplotlib import cbook, rcParams from matplotlib.axes import Axes import matplotlib.axis as maxis import matplotlib.markers as mmarkers import matplotlib.patches as mpatches import matplotlib.path as mpath -from matplotlib import rcParams import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.spines as mspines @@ -908,9 +908,7 @@ def _set_lim_and_transforms(self): self._r_label_position + self.transData) def get_xaxis_transform(self, which='grid'): - if which not in ['tick1', 'tick2', 'grid']: - raise ValueError( - "'which' must be one of 'tick1', 'tick2', or 'grid'") + cbook._check_in_list(['tick1', 'tick2', 'grid'], which=which) return self._xaxis_transform def get_xaxis_text1_transform(self, pad): @@ -925,8 +923,7 @@ def get_yaxis_transform(self, which='grid'): elif which == 'grid': return self._yaxis_transform else: - raise ValueError( - "'which' must be one of 'tick1', 'tick2', or 'grid'") + cbook._check_in_list(['tick1', 'tick2', 'grid'], which=which) def get_yaxis_text1_transform(self, pad): thetamin, thetamax = self._realViewLim.intervalx @@ -1085,8 +1082,9 @@ def set_theta_direction(self, direction): elif direction in ('counterclockwise', 'anticlockwise', 1): mtx[0, 0] = 1 else: - raise ValueError( - "direction must be 1, -1, clockwise or counterclockwise") + cbook._check_in_list( + [-1, 1, 'clockwise', 'counterclockwise', 'anticlockwise'], + direction=direction) self._direction.invalidate() def get_theta_direction(self): diff --git a/lib/matplotlib/quiver.py b/lib/matplotlib/quiver.py index 512daaa5b4c1..fb1b784a8d68 100644 --- a/lib/matplotlib/quiver.py +++ b/lib/matplotlib/quiver.py @@ -459,10 +459,7 @@ def __init__(self, ax, *args, if pivot.lower() == 'mid': pivot = 'middle' self.pivot = pivot.lower() - if self.pivot not in self._PIVOT_VALS: - raise ValueError( - 'pivot must be one of {keys}, you passed {inp}'.format( - keys=self._PIVOT_VALS, inp=pivot)) + cbook._check_in_list(self._PIVOT_VALS, pivot=self.pivot) self.transform = kw.pop('transform', ax.transData) kw.setdefault('facecolors', color) diff --git a/lib/matplotlib/scale.py b/lib/matplotlib/scale.py index 8ce9b68a7165..93bb610fb4ef 100644 --- a/lib/matplotlib/scale.py +++ b/lib/matplotlib/scale.py @@ -349,10 +349,12 @@ def __init__(self, axis, **kwargs): base = kwargs.pop('basex', 10.0) subs = kwargs.pop('subsx', None) nonpos = kwargs.pop('nonposx', 'clip') + cbook._check_in_list(['mask', 'clip'], nonposx=nonpos) else: base = kwargs.pop('basey', 10.0) subs = kwargs.pop('subsy', None) nonpos = kwargs.pop('nonposy', 'clip') + cbook._check_in_list(['mask', 'clip'], nonposy=nonpos) if len(kwargs): raise ValueError(("provided too many kwargs, can only pass " @@ -360,8 +362,6 @@ def __init__(self, axis, **kwargs): "{'basey', 'subsy', nonposy'}. You passed ") + "{!r}".format(kwargs)) - if nonpos not in ['mask', 'clip']: - raise ValueError("nonposx, nonposy kwarg must be 'mask' or 'clip'") if base <= 0 or base == 1: raise ValueError('The log base cannot be <= 0 or == 1') @@ -664,9 +664,7 @@ def __init__(self, axis, nonpos='mask'): values beyond ]0, 1[ can be masked as invalid, or clipped to a number very close to 0 or 1 """ - if nonpos not in ['mask', 'clip']: - raise ValueError("nonposx, nonposy kwarg must be 'mask' or 'clip'") - + cbook._check_in_list(['mask', 'clip'], nonpos=nonpos) self._transform = LogitTransform(nonpos) def get_transform(self): diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index afc845f4ee2a..650689cdb629 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -939,10 +939,7 @@ def set_horizontalalignment(self, align): ---------- align : {'center', 'right', 'left'} """ - legal = ('center', 'right', 'left') - if align not in legal: - raise ValueError('Horizontal alignment must be one of %s' % - str(legal)) + cbook._check_in_list(['center', 'right', 'left'], align=align) self._horizontalalignment = align self.stale = True @@ -957,10 +954,7 @@ def set_multialignment(self, align): ---------- align : {'left', 'right', 'center'} """ - legal = ('center', 'right', 'left') - if align not in legal: - raise ValueError('Horizontal alignment must be one of %s' % - str(legal)) + cbook._check_in_list(['center', 'right', 'left'], align=align) self._multialignment = align self.stale = True @@ -1128,11 +1122,9 @@ def set_verticalalignment(self, align): ---------- align : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} """ - legal = ('top', 'bottom', 'center', 'baseline', 'center_baseline') - if align not in legal: - raise ValueError('Vertical alignment must be one of %s' % - str(legal)) - + cbook._check_in_list( + ['top', 'bottom', 'center', 'baseline', 'center_baseline'], + align=align) self._verticalalignment = align self.stale = True @@ -1690,8 +1682,7 @@ def set_unit(self, unit): ---------- unit : {'points', 'pixels'} ''' - if unit not in ["points", "pixels"]: - raise ValueError("'unit' must be one of [ 'points' | 'pixels' ]") + cbook._check_in_list(["points", "pixels"], unit=unit) self._unit = unit def get_unit(self): diff --git a/lib/matplotlib/tri/tripcolor.py b/lib/matplotlib/tri/tripcolor.py index 71f5d2de6dc9..52dd3e9e2ba9 100644 --- a/lib/matplotlib/tri/tripcolor.py +++ b/lib/matplotlib/tri/tripcolor.py @@ -1,5 +1,6 @@ import numpy as np +from matplotlib import cbook from matplotlib.collections import PolyCollection, TriMesh from matplotlib.colors import Normalize from matplotlib.tri.triangulation import Triangulation @@ -46,9 +47,7 @@ def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None, The remaining kwargs are the same as for :meth:`~matplotlib.axes.Axes.pcolor`. """ - if shading not in ['flat', 'gouraud']: - raise ValueError("shading must be one of ['flat', 'gouraud'] " - "not {0}".format(shading)) + cbook._check_in_list(['flat', 'gouraud'], shading=shading) tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs) diff --git a/lib/matplotlib/widgets.py b/lib/matplotlib/widgets.py index 009998a53680..c4b6b82010b8 100644 --- a/lib/matplotlib/widgets.py +++ b/lib/matplotlib/widgets.py @@ -14,7 +14,7 @@ import numpy as np -from . import rcParams +from . import cbook, rcParams from .lines import Line2D from .patches import Circle, Rectangle, Ellipse from .transforms import blended_transform_factory @@ -1760,8 +1760,7 @@ def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops['animated'] = self.useblit - if direction not in ['horizontal', 'vertical']: - raise ValueError("direction must be 'horizontal' or 'vertical'") + cbook._check_in_list(['horizontal', 'vertical'], direction=direction) self.direction = direction self.rect = None @@ -2109,9 +2108,7 @@ def __init__(self, ax, onselect, drawtype='box', self.minspanx = minspanx self.minspany = minspany - if spancoords not in ('data', 'pixels'): - raise ValueError("'spancoords' must be 'data' or 'pixels'") - + cbook._check_in_list(['data', 'pixels'], spancoords=spancoords) self.spancoords = spancoords self.drawtype = drawtype @@ -2193,7 +2190,8 @@ def _release(self, event): xmin, ymin = self.eventpress.x, self.eventpress.y xmax, ymax = self.eventrelease.x, self.eventrelease.y else: - raise ValueError('spancoords must be "data" or "pixels"') + cbook._check_in_list(['data', 'pixels'], + spancoords=self.spancoords) if xmin > xmax: xmin, xmax = xmax, xmin diff --git a/lib/mpl_toolkits/axes_grid1/axes_divider.py b/lib/mpl_toolkits/axes_grid1/axes_divider.py index 40fb5af9b231..cfaf9235d6bd 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_divider.py +++ b/lib/mpl_toolkits/axes_grid1/axes_divider.py @@ -267,7 +267,6 @@ def new_locator(self, nx, ny, nx1=None, ny1=None): return AxesLocator(self, nx, ny, nx1, ny1) def append_size(self, position, size): - if position == "left": self._horizontal.insert(0, size) self._xrefindex += 1 @@ -279,8 +278,8 @@ def append_size(self, position, size): elif position == "top": self._vertical.append(size) else: - raise ValueError("the position must be one of left," + - " right, bottom, or top") + cbook._check_in_list(["left", "right", "bottom", "top"], + position=position) def add_auto_adjustable_area(self, use_axes, pad=0.1, @@ -613,7 +612,6 @@ def append_axes(self, position, size, pad=None, add_to_figure=True, *size* and *pad* should be axes_grid.axes_size compatible. """ - if position == "left": ax = self.new_horizontal(size, pad, pack_start=True, **kwargs) elif position == "right": @@ -623,9 +621,8 @@ def append_axes(self, position, size, pad=None, add_to_figure=True, elif position == "top": ax = self.new_vertical(size, pad, pack_start=False, **kwargs) else: - raise ValueError("the position must be one of left," + - " right, bottom, or top") - + cbook._check_in_list(["left", "right", "bottom", "top"], + position=position) if add_to_figure: self._fig.add_axes(ax) return ax diff --git a/lib/mpl_toolkits/axes_grid1/axes_size.py b/lib/mpl_toolkits/axes_grid1/axes_size.py index 91aa4123f04f..4edc50d323fc 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_size.py +++ b/lib/mpl_toolkits/axes_grid1/axes_size.py @@ -1,5 +1,5 @@ """ -Provides a classes of simple units that will be used with AxesDivider +Provides classes of simple units that will be used with AxesDivider class (or others) to determine the size of each axes. The unit classes define `get_size` method that returns a tuple of two floats, meaning relative and absolute sizes, respectively. @@ -11,6 +11,7 @@ class (or others) to determine the size of each axes. The unit from numbers import Number +from matplotlib import cbook from matplotlib.axes import Axes @@ -303,8 +304,7 @@ class GetExtentHelper(object): } def __init__(self, ax, direction): - if direction not in self._get_func_map: - raise KeyError("direction must be one of left, right, bottom, top") + cbook._check_in_list(self._get_func_map, direction=direction) self._ax_list = [ax] if isinstance(ax, Axes) else ax self._direction = direction diff --git a/lib/mpl_toolkits/axes_grid1/parasite_axes.py b/lib/mpl_toolkits/axes_grid1/parasite_axes.py index ccdd4b8a4034..de9e68856065 100644 --- a/lib/mpl_toolkits/axes_grid1/parasite_axes.py +++ b/lib/mpl_toolkits/axes_grid1/parasite_axes.py @@ -1,6 +1,6 @@ import functools -from matplotlib import artist as martist, transforms as mtransforms +from matplotlib import artist as martist, cbook, transforms as mtransforms from matplotlib.axes import subplot_class_factory from matplotlib.transforms import Bbox from .mpl_axes import Axes @@ -82,10 +82,8 @@ def _set_lim_and_transforms(self): self.transAxes, self.transData) def set_viewlim_mode(self, mode): - if mode not in [None, "equal", "transform"]: - raise ValueError("Unknown mode: %s" % (mode,)) - else: - self._viewlim_mode = mode + cbook._check_in_list([None, "equal", "transform"], mode=mode) + self._viewlim_mode = mode def get_viewlim_mode(self): return self._viewlim_mode @@ -101,7 +99,7 @@ def update_viewlim(self): self.axes.viewLim.set( viewlim.transformed(self.transAux.inverted())) else: - raise ValueError("Unknown mode: %s" % (self._viewlim_mode,)) + cbook._check_in_list([None, "equal", "transform"], mode=mode) def _pcolor(self, super_pcolor, *XYC, **kwargs): if len(XYC) == 1: diff --git a/lib/mpl_toolkits/axisartist/axis_artist.py b/lib/mpl_toolkits/axisartist/axis_artist.py index 219e4306a3ec..585a700b5ccc 100644 --- a/lib/mpl_toolkits/axisartist/axis_artist.py +++ b/lib/mpl_toolkits/axisartist/axis_artist.py @@ -463,9 +463,7 @@ def get_text(self): top=("bottom", "center")) def set_default_alignment(self, d): - if d not in ["left", "right", "top", "bottom"]: - raise ValueError( - 'direction must be on of "left", "right", "top", "bottom"') + cbook._check_in_list(["left", "right", "top", "bottom"], d=d) va, ha = self._default_alignments[d] self.set_va(va) self.set_ha(ha) @@ -476,9 +474,7 @@ def set_default_alignment(self, d): top=180) def set_default_angle(self, d): - if d not in ["left", "right", "top", "bottom"]: - raise ValueError( - 'direction must be on of "left", "right", "top", "bottom"') + cbook._check_in_list(["left", "right", "top", "bottom"], d=d) self.set_rotation(self._default_angles[d]) def set_axis_direction(self, d): @@ -500,9 +496,7 @@ def set_axis_direction(self, d): axis. """ - if d not in ["left", "right", "top", "bottom"]: - raise ValueError( - 'direction must be on of "left", "right", "top", "bottom"') + cbook._check_in_list(["left", "right", "top", "bottom"], d=d) self.set_default_alignment(d) self.set_default_angle(d) @@ -558,8 +552,7 @@ def set_axis_direction(self, label_direction): Adjust the text angle and text alignment of ticklabels according to the matplotlib convention. - The *label_direction* must be one of [left, right, bottom, - top]. + The *label_direction* must be one of [left, right, bottom, top]. ===================== ========== ========= ========== ========== property left bottom right top @@ -569,15 +562,12 @@ def set_axis_direction(self, label_direction): ticklabel ha right center right center ===================== ========== ========= ========== ========== - Note that the text angles are actually relative to (90 + angle of the direction to the ticklabel), which gives 0 for bottom axis. """ - - if label_direction not in ["left", "right", "top", "bottom"]: - raise ValueError( - 'direction must be one of "left", "right", "top", "bottom"') + cbook._check_in_list(["left", "right", "top", "bottom"], + label_direction=label_direction) self._axis_direction = label_direction self.set_default_alignment(label_direction) self.set_default_angle(label_direction) @@ -831,8 +821,7 @@ def set_axis_direction(self, axis_direction): ticklabels, labels following the matplotlib convention for the rectangle axes. - The *axis_direction* must be one of [left, right, bottom, - top]. + The *axis_direction* must be one of [left, right, bottom, top]. ===================== ========== ========= ========== ========== property left bottom right top @@ -847,17 +836,13 @@ def set_axis_direction(self, axis_direction): axislabel ha right center right center ===================== ========== ========= ========== ========== - Note that the direction "+" and "-" are relative to the direction of the increasing coordinate. Also, the text angles are actually relative to (90 + angle of the direction to the ticklabel), which gives 0 for bottom axis. - """ - - if axis_direction not in ["left", "right", "top", "bottom"]: - raise ValueError( - 'direction must be on of "left", "right", "top", "bottom"') + cbook._check_in_list(["left", "right", "top", "bottom"], + axis_direction=axis_direction) self._axis_direction = axis_direction if axis_direction in ["left", "top"]: self.set_ticklabel_direction("-") @@ -865,7 +850,6 @@ def set_axis_direction(self, axis_direction): else: self.set_ticklabel_direction("+") self.set_axislabel_direction("+") - self.major_ticklabels.set_axis_direction(axis_direction) self.label.set_axis_direction(axis_direction) @@ -880,14 +864,8 @@ def set_ticklabel_direction(self, tick_direction): ---------- tick_direction : {"+", "-"} """ - - if tick_direction not in ["+", "-"]: - raise ValueError('direction must be one of "+", "-"') - - if tick_direction == "-": - self._ticklabel_add_angle = 180 - else: - self._ticklabel_add_angle = 0 + cbook._check_in_list(["+", "-"], tick_direction=tick_direction) + self._ticklabel_add_angle = {"+": 0, "-": 180}[tick_direction] def invert_ticklabel_direction(self): self._ticklabel_add_angle = (self._ticklabel_add_angle + 180) % 360 @@ -905,13 +883,8 @@ def set_axislabel_direction(self, label_direction): ---------- tick_direction : {"+", "-"} """ - if label_direction not in ["+", "-"]: - raise ValueError('direction must be one of "+", "-"') - - if label_direction == "-": - self._axislabel_add_angle = 180 - else: - self._axislabel_add_angle = 0 + cbook._check_in_list(["+", "-"], label_direction=label_direction) + self._axislabel_add_angle = {"+": 0, "-": 180}[label_direction] def get_transform(self): return self.axes.transAxes + self.offset_transform diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index dd31670fd58e..f11e8de8e53e 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -1405,8 +1405,7 @@ def tick_params(self, axis='both', **kwargs): .. versionadded :: 1.1.0 This function was added, but not tested. Please report any bugs. """ - if axis not in ['x', 'y', 'z', 'both']: - raise ValueError("axis must be one of 'x', 'y', 'z' or 'both'") + cbook._check_in_list(['x', 'y', 'z', 'both'], axis=axis) if axis in ['x', 'y', 'both']: super().tick_params(axis, **kwargs) if axis in ['z', 'both']: