Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Move cbook._check_in_list() to _api.check_in_list() #18494

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
Sep 17, 2020
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
33 changes: 33 additions & 0 deletions lib/matplotlib/_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@


def check_in_list(_values, *, _print_supported_values=True, **kwargs):
"""
For each *key, value* pair in *kwargs*, check that *value* is in *_values*.

Parameters
----------
_values : iterable
Sequence of values to check on.
_print_supported_values : bool, default: True
Whether to print *_values* when raising ValueError.
**kwargs : dict
*key, value* pairs as keyword arguments to find in *_values*.

Raises
------
ValueError
If any *value* in *kwargs* is not found in *_values*.

Examples
--------
>>> _api.check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg)
"""
values = _values
for key, val in kwargs.items():
if val not in values:
if _print_supported_values:
raise ValueError(
f"{val!r} is not a valid value for {key}; "
f"supported values are {', '.join(map(repr, values))}")
else:
raise ValueError(f"{val!r} is not a valid value for {key}")
9 changes: 4 additions & 5 deletions lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import matplotlib as mpl
from matplotlib._animation_data import (
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
from matplotlib import cbook
from matplotlib import _api, cbook


_log = logging.getLogger(__name__)
Expand Down Expand Up @@ -797,8 +797,8 @@ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
extra_args = () # Don't lookup nonexistent rcParam[args_key].
self.embed_frames = embed_frames
self.default_mode = default_mode.lower()
cbook._check_in_list(['loop', 'once', 'reflect'],
default_mode=self.default_mode)
_api.check_in_list(['loop', 'once', 'reflect'],
default_mode=self.default_mode)

# Save embed limit, which is given in MB
if embed_limit is None:
Expand All @@ -812,8 +812,7 @@ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,

def setup(self, fig, outfile, dpi, frame_dir=None):
outfile = Path(outfile)
cbook._check_in_list(['.html', '.htm'],
outfile_extension=outfile.suffix)
_api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)

self._saved_frames = []
self._total_bytes = 0
Expand Down
25 changes: 11 additions & 14 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
import matplotlib.transforms as mtransforms
import matplotlib.tri as mtri
import matplotlib.units as munits
from matplotlib import _preprocess_data, rcParams
from matplotlib import _api, _preprocess_data, rcParams
from matplotlib.axes._base import (
_AxesBase, _TransformedBoundsLocator, _process_plot_format)
from matplotlib.axes._secondary_axes import SecondaryAxis
Expand Down Expand Up @@ -2084,7 +2084,7 @@ def step(self, x, y, *args, where='pre', data=None, **kwargs):
-----
.. [notes section required to get data note injection right]
"""
cbook._check_in_list(('pre', 'post', 'mid'), where=where)
_api.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 @@ -2269,8 +2269,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
# logic and drawing to bar(). It is considered internal and is
# intentionally not mentioned in the docstring.
orientation = kwargs.pop('orientation', 'vertical')
cbook._check_in_list(['vertical', 'horizontal'],
orientation=orientation)
_api.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 @@ -2334,7 +2333,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)
_api.check_in_list(['center', 'edge'], align=align)
if align == 'center':
if orientation == 'vertical':
try:
Expand Down Expand Up @@ -2680,8 +2679,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
if not 1 <= len(args) <= 5:
raise TypeError('stem expected between 1 and 5 positional '
'arguments, got {}'.format(args))
cbook._check_in_list(['horizontal', 'vertical'],
orientation=orientation)
_api.check_in_list(['horizontal', 'vertical'], orientation=orientation)

if len(args) == 1:
heads, = args
Expand Down Expand Up @@ -5467,7 +5465,7 @@ def _pcolorargs(funcname, *args, shading='flat'):

_valid_shading = ['gouraud', 'nearest', 'flat', 'auto']
try:
cbook._check_in_list(_valid_shading, shading=shading)
_api.check_in_list(_valid_shading, shading=shading)
except ValueError as err:
cbook._warn_external(f"shading value '{shading}' not in list of "
f"valid values {_valid_shading}. Setting "
Expand Down Expand Up @@ -6487,11 +6485,10 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
bins = rcParams['hist.bins']

# Validate string inputs here to avoid cluttering subsequent code.
cbook._check_in_list(['bar', 'barstacked', 'step', 'stepfilled'],
histtype=histtype)
cbook._check_in_list(['left', 'mid', 'right'], align=align)
cbook._check_in_list(['horizontal', 'vertical'],
orientation=orientation)
_api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'],
histtype=histtype)
_api.check_in_list(['left', 'mid', 'right'], align=align)
_api.check_in_list(['horizontal', 'vertical'], orientation=orientation)

if histtype == 'barstacked' and not stacked:
stacked = True
Expand Down Expand Up @@ -7574,7 +7571,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
"""
if marker is None and markersize is None and hasattr(Z, 'tocoo'):
marker = 's'
cbook._check_in_list(["upper", "lower"], origin=origin)
_api.check_in_list(["upper", "lower"], origin=origin)
if marker is None and markersize is None:
Z = np.asarray(Z)
mask = np.abs(Z) > precision
Expand Down
14 changes: 7 additions & 7 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import numpy as np

import matplotlib as mpl
from matplotlib import cbook
from matplotlib import _api, cbook
from matplotlib.cbook import _OrderedSet, _check_1d, index_of
from matplotlib import docstring
import matplotlib.colors as mcolors
Expand Down Expand Up @@ -1443,7 +1443,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.
"""
cbook._check_in_list(["box", "datalim"], adjustable=adjustable)
_api.check_in_list(["box", "datalim"], adjustable=adjustable)
if share:
axs = {*self._shared_x_axes.get_siblings(self),
*self._shared_y_axes.get_siblings(self)}
Expand Down Expand Up @@ -2941,7 +2941,7 @@ def grid(self, b=None, which='major', axis='both', **kwargs):
"""
if len(kwargs):
b = True
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
_api.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']:
Expand Down Expand Up @@ -3055,7 +3055,7 @@ def locator_params(self, axis='both', tight=None, **kwargs):
ax.locator_params(tight=True, nbins=4)

"""
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
_api.check_in_list(['x', 'y', 'both'], axis=axis)
update_x = axis in ['x', 'both']
update_y = axis in ['y', 'both']
if update_x:
Expand Down Expand Up @@ -3129,7 +3129,7 @@ def tick_params(self, axis='both', **kwargs):
also be red. Gridlines will be red and translucent.

"""
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
_api.check_in_list(['x', 'y', 'both'], axis=axis)
if axis in ['x', 'both']:
xkw = dict(kwargs)
xkw.pop('left', None)
Expand Down Expand Up @@ -3212,7 +3212,7 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
else:
loc = (loc if loc is not None
else mpl.rcParams['xaxis.labellocation'])
cbook._check_in_list(('left', 'center', 'right'), loc=loc)
_api.check_in_list(('left', 'center', 'right'), loc=loc)
if loc == 'left':
kwargs.update(x=0, horizontalalignment='left')
elif loc == 'right':
Expand Down Expand Up @@ -3555,7 +3555,7 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
else:
loc = (loc if loc is not None
else mpl.rcParams['yaxis.labellocation'])
cbook._check_in_list(('bottom', 'center', 'top'), loc=loc)
_api.check_in_list(('bottom', 'center', 'top'), loc=loc)
if loc == 'bottom':
kwargs.update(y=0, horizontalalignment='left')
elif loc == 'top':
Expand Down
3 changes: 2 additions & 1 deletion lib/matplotlib/axes/_secondary_axes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np

from matplotlib import _api
import matplotlib.cbook as cbook
import matplotlib.docstring as docstring
import matplotlib.ticker as mticker
Expand Down Expand Up @@ -69,7 +70,7 @@ def set_alignment(self, align):
either 'top' or 'bottom' for orientation='x' or
'left' or 'right' for orientation='y' axis.
"""
cbook._check_in_list(self._locstrings, align=align)
_api.check_in_list(self._locstrings, align=align)
if align == self._locstrings[1]: # Need to change the orientation.
self._locstrings = self._locstrings[::-1]
self.spines[self._locstrings[0]].set_visible(True)
Expand Down
19 changes: 10 additions & 9 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import numpy as np

import matplotlib as mpl
from matplotlib import _api
import matplotlib.artist as martist
import matplotlib.cbook as cbook
import matplotlib.lines as mlines
Expand Down Expand Up @@ -206,7 +207,7 @@ def _set_labelrotation(self, labelrotation):
else:
mode = 'default'
angle = labelrotation
cbook._check_in_list(['auto', 'default'], labelrotation=mode)
_api.check_in_list(['auto', 'default'], labelrotation=mode)
self._labelrotation = (mode, angle)

def apply_tickdir(self, tickdir):
Expand Down Expand Up @@ -456,7 +457,7 @@ def apply_tickdir(self, tickdir):
"""Set tick direction. Valid values are 'in', 'out', 'inout'."""
if tickdir is None:
tickdir = mpl.rcParams['%s.direction' % self.__name__.lower()]
cbook._check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
_api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
self._tickdir = tickdir

if self._tickdir == 'in':
Expand Down Expand Up @@ -819,7 +820,7 @@ def set_tick_params(self, which='major', reset=False, **kw):
For documentation of keyword arguments, see
:meth:`matplotlib.axes.Axes.tick_params`.
"""
cbook._check_in_list(['major', 'minor', 'both'], which=which)
_api.check_in_list(['major', 'minor', 'both'], which=which)
kwtrans = self._translate_tick_kw(kw)

# the kwargs are stored in self._major/minor_tick_kw so that any
Expand Down Expand Up @@ -1249,7 +1250,7 @@ def get_ticklabels(self, minor=False, which=None):
elif which == 'both':
return self.get_majorticklabels() + self.get_minorticklabels()
else:
cbook._check_in_list(['major', 'minor', 'both'], which=which)
_api.check_in_list(['major', 'minor', 'both'], which=which)
if minor:
return self.get_minorticklabels()
return self.get_majorticklabels()
Expand Down Expand Up @@ -1429,7 +1430,7 @@ def grid(self, b=None, which='major', **kwargs):
'grid will be enabled.')
b = True
which = which.lower()
cbook._check_in_list(['major', 'minor', 'both'], which=which)
_api.check_in_list(['major', 'minor', 'both'], which=which)
gridkw = {'grid_' + item[0]: item[1] for item in kwargs.items()}

if which in ['minor', 'both']:
Expand Down Expand Up @@ -2174,8 +2175,8 @@ def set_ticks_position(self, position):
can be used if you don't want any ticks. 'none' and 'both'
affect only the ticks, not the labels.
"""
cbook._check_in_list(['top', 'bottom', 'both', 'default', 'none'],
position=position)
_api.check_in_list(['top', 'bottom', 'both', 'default', 'none'],
position=position)
if position == 'top':
self.set_tick_params(which='both', top=True, labeltop=True,
bottom=False, labelbottom=False)
Expand Down Expand Up @@ -2461,8 +2462,8 @@ def set_ticks_position(self, position):
can be used if you don't want any ticks. 'none' and 'both'
affect only the ticks, not the labels.
"""
cbook._check_in_list(['left', 'right', 'both', 'default', 'none'],
position=position)
_api.check_in_list(['left', 'right', 'both', 'default', 'none'],
position=position)
if position == 'right':
self.set_tick_params(which='both', right=True, labelright=True,
left=False, labelleft=False)
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@

import matplotlib as mpl
from matplotlib import (
backend_tools as tools, cbook, colors, textpath, tight_bbox,
_api, backend_tools as tools, cbook, colors, textpath, tight_bbox,
transforms, widgets, get_backend, is_interactive, rcParams)
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_managers import ToolManager
Expand Down Expand Up @@ -914,7 +914,7 @@ def set_antialiased(self, b):

def set_capstyle(self, cs):
"""Set the capstyle to be one of ('butt', 'round', 'projecting')."""
cbook._check_in_list(['butt', 'round', 'projecting'], cs=cs)
_api.check_in_list(['butt', 'round', 'projecting'], cs=cs)
self._capstyle = cs

def set_clip_rectangle(self, rectangle):
Expand Down Expand Up @@ -982,7 +982,7 @@ def set_foreground(self, fg, isRGBA=False):

def set_joinstyle(self, js):
"""Set the join style to be one of ('miter', 'round', 'bevel')."""
cbook._check_in_list(['miter', 'round', 'bevel'], js=js)
_api.check_in_list(['miter', 'round', 'bevel'], js=js)
self._joinstyle = js

def set_linewidth(self, w):
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import numpy as np

import matplotlib as mpl
from matplotlib import cbook, _path
from matplotlib import _api, cbook, _path
from matplotlib import _text_layout
from matplotlib.afm import AFM
from matplotlib.backend_bases import (
Expand Down Expand Up @@ -815,7 +815,7 @@ def _print_ps(
if papertype is None:
papertype = mpl.rcParams['ps.papersize']
papertype = papertype.lower()
cbook._check_in_list(['auto', *papersize], papertype=papertype)
_api.check_in_list(['auto', *papersize], papertype=papertype)

orientation = cbook._check_getitem(
_Orientation, orientation=orientation.lower())
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_webagg_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from PIL import Image
import tornado

from matplotlib import backend_bases, cbook
from matplotlib import _api, backend_bases
from matplotlib.backends import backend_agg
from matplotlib.backend_bases import _Backend

Expand Down Expand Up @@ -165,7 +165,7 @@ def set_image_mode(self, mode):
draw this mode may be changed if the resulting image has any
transparent component.
"""
cbook._check_in_list(['full', 'diff'], mode=mode)
_api.check_in_list(['full', 'diff'], mode=mode)
if self._current_image_mode != mode:
self._current_image_mode = mode
self.handle_send_image_mode(None)
Expand Down
Loading