Skip to content

Commit c0f839b

Browse files
committed
Add helper function to check that an argument is in a list of strings.
1 parent 49c9904 commit c0f839b

File tree

25 files changed

+121
-191
lines changed

25 files changed

+121
-191
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Changed exceptions
2+
``````````````````
3+
4+
- `mpl_toolkits.axes_grid1.axes_size.GetExtentHelper` now raises `ValueError`
5+
for invalid directions instead of `KeyError`.

lib/matplotlib/axes/_base.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,8 +1328,7 @@ def set_adjustable(self, adjustable, share=False):
13281328
which the adjustments for aspect ratios are done sequentially
13291329
and independently on each Axes as it is drawn.
13301330
"""
1331-
if adjustable not in ('box', 'datalim'):
1332-
raise ValueError("argument must be 'box', or 'datalim'")
1331+
cbook._check_in_list(["box", "datalim"], adjustable=adjustable)
13331332
if share:
13341333
axes = set(self._shared_x_axes.get_siblings(self)
13351334
+ self._shared_y_axes.get_siblings(self))
@@ -2745,9 +2744,7 @@ def grid(self, b=None, which='major', axis='both', **kwargs):
27452744
"""
27462745
if len(kwargs):
27472746
b = True
2748-
if axis not in ['x', 'y', 'both']:
2749-
raise ValueError("The argument 'axis' must be one of 'x', 'y' or "
2750-
"'both'.")
2747+
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
27512748
if axis in ['x', 'both']:
27522749
self.xaxis.grid(b, which=which, **kwargs)
27532750
if axis in ['y', 'both']:
@@ -2963,8 +2960,7 @@ def tick_params(self, axis='both', **kwargs):
29632960
also be red. Gridlines will be red and translucent.
29642961
29652962
"""
2966-
if axis not in ['x', 'y', 'both']:
2967-
raise ValueError("axis must be one of 'x', 'y' or 'both'")
2963+
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
29682964
if axis in ['x', 'both']:
29692965
xkw = dict(kwargs)
29702966
xkw.pop('left', None)

lib/matplotlib/axes/_subplots.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import functools
22
import uuid
33

4-
from matplotlib import docstring
4+
from matplotlib import cbook, docstring
55
import matplotlib.artist as martist
66
from matplotlib.axes._axes import Axes
77
from matplotlib.gridspec import GridSpec, SubplotSpec

lib/matplotlib/axis.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -204,9 +204,7 @@ def _set_labelrotation(self, labelrotation):
204204
else:
205205
mode = 'default'
206206
angle = labelrotation
207-
if mode not in ('auto', 'default'):
208-
raise ValueError("Label rotation mode must be 'default' or "
209-
"'auto', not '{}'.".format(mode))
207+
cbook._check_in_list(['auto', 'default'], labelrotation=mode)
210208
self._labelrotation = (mode, angle)
211209

212210
def apply_tickdir(self, tickdir):
@@ -1269,8 +1267,7 @@ def get_ticklabels(self, minor=False, which=None):
12691267
elif which == 'both':
12701268
return self.get_majorticklabels() + self.get_minorticklabels()
12711269
else:
1272-
raise ValueError("`which` must be one of ('minor', 'major', "
1273-
"'both') not " + str(which))
1270+
cbook._check_in_list(['major', 'minor', 'both'], which=which)
12741271
if minor:
12751272
return self.get_minorticklabels()
12761273
return self.get_majorticklabels()
@@ -1426,9 +1423,7 @@ def grid(self, b=None, which='major', **kwargs):
14261423
'grid will be enabled.')
14271424
b = True
14281425
which = which.lower()
1429-
if which not in ['major', 'minor', 'both']:
1430-
raise ValueError("The argument 'which' must be one of 'major', "
1431-
"'minor' or 'both'.")
1426+
cbook._check_in_list(['major', 'minor', 'both'], which=which)
14321427
gridkw = {'grid_' + item[0]: item[1] for item in kwargs.items()}
14331428

14341429
if which in ['minor', 'both']:

lib/matplotlib/backends/backend_ps.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -838,12 +838,9 @@ def _print_ps(self, outfile, format, *args,
838838
(papertype, ', '.join(papersize)))
839839

840840
orientation = orientation.lower()
841-
if orientation == 'landscape':
842-
isLandscape = True
843-
elif orientation == 'portrait':
844-
isLandscape = False
845-
else:
846-
raise RuntimeError('Orientation must be "portrait" or "landscape"')
841+
cbook._check_in_list(['landscape', 'portrait'],
842+
orientation=orientation)
843+
isLandscape = (orientation == 'landscape')
847844

848845
self.figure.set_dpi(72) # Override the dpi kwarg
849846

lib/matplotlib/backends/backend_webagg_core.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
import numpy as np
2121
import tornado
2222

23+
from matplotlib import backend_bases, cbook, _png
2324
from matplotlib.backends import backend_agg
2425
from matplotlib.backend_bases import _Backend
25-
from matplotlib import backend_bases, _png
2626

2727
_log = logging.getLogger(__name__)
2828

@@ -163,10 +163,8 @@ def set_image_mode(self, mode):
163163
Note: diff images may not contain transparency, therefore upon
164164
draw this mode may be changed if the resulting image has any
165165
transparent component.
166-
167166
"""
168-
if mode not in ['full', 'diff']:
169-
raise ValueError('image mode must be either full or diff.')
167+
cbook._check_in_list(['full', 'diff'], mode=mode)
170168
if self._current_image_mode != mode:
171169
self._current_image_mode = mode
172170
self.handle_send_image_mode(None)

lib/matplotlib/cbook/__init__.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2111,6 +2111,12 @@ def _unmultiplied_rgba8888_to_premultiplied_argb32(rgba8888):
21112111

21122112

21132113
def _check_and_log_subprocess(command, logger, **kwargs):
2114+
"""
2115+
Run *command* using `subprocess.check_output`. If it succeeds, return the
2116+
output (stdout and stderr); if not, raise an exception whose text includes
2117+
the failed command and captured output. Both the command and the output
2118+
are logged at DEBUG level on *logger*.
2119+
"""
21142120
logger.debug(command)
21152121
try:
21162122
report = subprocess.check_output(
@@ -2134,3 +2140,19 @@ def _check_not_matrix(**kwargs):
21342140
for k, v in kwargs.items():
21352141
if isinstance(v, np.matrix):
21362142
raise TypeError(f"Argument {k!r} cannot be a np.matrix")
2143+
2144+
2145+
def _check_in_list(values, **kwargs):
2146+
"""
2147+
For each *key, value* pair in *kwargs*, check that *value* is in *values*;
2148+
if not, raise an appropriate ValueError.
2149+
2150+
Examples
2151+
--------
2152+
>>> cbook._check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg)
2153+
"""
2154+
for k, v in kwargs.items():
2155+
if v not in values:
2156+
raise ValueError(
2157+
"{!r} is not a valid value for {}; supported values are {}"
2158+
.format(v, k, ', '.join(map(repr, values))))

lib/matplotlib/collections.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -464,8 +464,8 @@ def set_offset_position(self, offset_position):
464464
----------
465465
offset_position : {'screen', 'data'}
466466
"""
467-
if offset_position not in ('screen', 'data'):
468-
raise ValueError("offset_position must be 'screen' or 'data'")
467+
cbook._check_in_list(['screen', 'data'],
468+
offset_position=offset_position)
469469
self._offset_position = offset_position
470470
self.stale = True
471471

@@ -1490,7 +1490,8 @@ def __init__(self,
14901490
coord1 in positions]
14911491
self._is_horizontal = False
14921492
else:
1493-
raise ValueError("orientation must be 'horizontal' or 'vertical'")
1493+
cbook._check_in_list(['horizontal', 'vertical'],
1494+
orientation=orientation)
14941495

14951496
LineCollection.__init__(self,
14961497
segments,
@@ -1583,8 +1584,8 @@ def set_orientation(self, orientation=None):
15831584
elif orientation.lower() == 'vertical':
15841585
is_horizontal = False
15851586
else:
1586-
raise ValueError("orientation must be 'horizontal' or 'vertical'")
1587-
1587+
cbook._check_in_list(['horizontal', 'vertical'],
1588+
orientation=orientation)
15881589
if is_horizontal == self.is_horizontal():
15891590
return
15901591
self.switch_orientation()

lib/matplotlib/contour.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -842,9 +842,7 @@ def __init__(self, ax, *args,
842842
else:
843843
self.logscale = False
844844

845-
if self.origin not in [None, 'lower', 'upper', 'image']:
846-
raise ValueError("If given, *origin* must be one of [ 'lower' |"
847-
" 'upper' | 'image']")
845+
cbook._check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
848846
if self.extent is not None and len(self.extent) != 4:
849847
raise ValueError("If given, *extent* must be '[ *None* |"
850848
" (x0,x1,y0,y1) ]'")

lib/matplotlib/figure.py

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1524,23 +1524,17 @@ def subplots(self, nrows=1, ncols=1, sharex=False, sharey=False,
15241524
sharex = "all" if sharex else "none"
15251525
if isinstance(sharey, bool):
15261526
sharey = "all" if sharey else "none"
1527-
share_values = ["all", "row", "col", "none"]
1528-
if sharex not in share_values:
1529-
# This check was added because it is very easy to type
1530-
# `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended.
1531-
# In most cases, no error will ever occur, but mysterious behavior
1532-
# will result because what was intended to be the subplot index is
1533-
# instead treated as a bool for sharex.
1534-
if isinstance(sharex, Integral):
1535-
cbook._warn_external("sharex argument to subplots() was an "
1536-
"integer. Did you intend to use "
1537-
"subplot() (without 's')?")
1538-
1539-
raise ValueError("sharex [%s] must be one of %s" %
1540-
(sharex, share_values))
1541-
if sharey not in share_values:
1542-
raise ValueError("sharey [%s] must be one of %s" %
1543-
(sharey, share_values))
1527+
# This check was added because it is very easy to type
1528+
# `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended.
1529+
# In most cases, no error will ever occur, but mysterious behavior
1530+
# will result because what was intended to be the subplot index is
1531+
# instead treated as a bool for sharex.
1532+
if isinstance(sharex, Integral):
1533+
cbook._warn_external(
1534+
"sharex argument to subplots() was an integer. Did you "
1535+
"intend to use subplot() (without 's')?")
1536+
cbook._check_in_list(["all", "row", "col", "none"],
1537+
sharex=sharex, sharey=sharey)
15441538
if subplot_kw is None:
15451539
subplot_kw = {}
15461540
if gridspec_kw is None:

0 commit comments

Comments
 (0)