Skip to content

Commit 4efdaac

Browse files
authored
Merge pull request #18494 from timhoffm/private-api
Move cbook._check_in_list() to _api.check_in_list()
2 parents 8676c27 + c4105dc commit 4efdaac

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+187
-194
lines changed

lib/matplotlib/_api.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
3+
def check_in_list(_values, *, _print_supported_values=True, **kwargs):
4+
"""
5+
For each *key, value* pair in *kwargs*, check that *value* is in *_values*.
6+
7+
Parameters
8+
----------
9+
_values : iterable
10+
Sequence of values to check on.
11+
_print_supported_values : bool, default: True
12+
Whether to print *_values* when raising ValueError.
13+
**kwargs : dict
14+
*key, value* pairs as keyword arguments to find in *_values*.
15+
16+
Raises
17+
------
18+
ValueError
19+
If any *value* in *kwargs* is not found in *_values*.
20+
21+
Examples
22+
--------
23+
>>> _api.check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg)
24+
"""
25+
values = _values
26+
for key, val in kwargs.items():
27+
if val not in values:
28+
if _print_supported_values:
29+
raise ValueError(
30+
f"{val!r} is not a valid value for {key}; "
31+
f"supported values are {', '.join(map(repr, values))}")
32+
else:
33+
raise ValueError(f"{val!r} is not a valid value for {key}")

lib/matplotlib/animation.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
import matplotlib as mpl
3636
from matplotlib._animation_data import (
3737
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
38-
from matplotlib import cbook
38+
from matplotlib import _api, cbook
3939

4040

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

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

813813
def setup(self, fig, outfile, dpi, frame_dir=None):
814814
outfile = Path(outfile)
815-
cbook._check_in_list(['.html', '.htm'],
816-
outfile_extension=outfile.suffix)
815+
_api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)
817816

818817
self._saved_frames = []
819818
self._total_bytes = 0

lib/matplotlib/axes/_axes.py

+11-14
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
import matplotlib.transforms as mtransforms
3131
import matplotlib.tri as mtri
3232
import matplotlib.units as munits
33-
from matplotlib import _preprocess_data, rcParams
33+
from matplotlib import _api, _preprocess_data, rcParams
3434
from matplotlib.axes._base import (
3535
_AxesBase, _TransformedBoundsLocator, _process_plot_format)
3636
from matplotlib.axes._secondary_axes import SecondaryAxis
@@ -2084,7 +2084,7 @@ def step(self, x, y, *args, where='pre', data=None, **kwargs):
20842084
-----
20852085
.. [notes section required to get data note injection right]
20862086
"""
2087-
cbook._check_in_list(('pre', 'post', 'mid'), where=where)
2087+
_api.check_in_list(('pre', 'post', 'mid'), where=where)
20882088
kwargs['drawstyle'] = 'steps-' + where
20892089
return self.plot(x, y, *args, data=data, **kwargs)
20902090

@@ -2269,8 +2269,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
22692269
# logic and drawing to bar(). It is considered internal and is
22702270
# intentionally not mentioned in the docstring.
22712271
orientation = kwargs.pop('orientation', 'vertical')
2272-
cbook._check_in_list(['vertical', 'horizontal'],
2273-
orientation=orientation)
2272+
_api.check_in_list(['vertical', 'horizontal'], orientation=orientation)
22742273
log = kwargs.pop('log', False)
22752274
label = kwargs.pop('label', '')
22762275
tick_labels = kwargs.pop('tick_label', None)
@@ -2334,7 +2333,7 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
23342333

23352334
# We will now resolve the alignment and really have
23362335
# left, bottom, width, height vectors
2337-
cbook._check_in_list(['center', 'edge'], align=align)
2336+
_api.check_in_list(['center', 'edge'], align=align)
23382337
if align == 'center':
23392338
if orientation == 'vertical':
23402339
try:
@@ -2680,8 +2679,7 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
26802679
if not 1 <= len(args) <= 5:
26812680
raise TypeError('stem expected between 1 and 5 positional '
26822681
'arguments, got {}'.format(args))
2683-
cbook._check_in_list(['horizontal', 'vertical'],
2684-
orientation=orientation)
2682+
_api.check_in_list(['horizontal', 'vertical'], orientation=orientation)
26852683

26862684
if len(args) == 1:
26872685
heads, = args
@@ -5467,7 +5465,7 @@ def _pcolorargs(funcname, *args, shading='flat'):
54675465

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

64896487
# Validate string inputs here to avoid cluttering subsequent code.
6490-
cbook._check_in_list(['bar', 'barstacked', 'step', 'stepfilled'],
6491-
histtype=histtype)
6492-
cbook._check_in_list(['left', 'mid', 'right'], align=align)
6493-
cbook._check_in_list(['horizontal', 'vertical'],
6494-
orientation=orientation)
6488+
_api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'],
6489+
histtype=histtype)
6490+
_api.check_in_list(['left', 'mid', 'right'], align=align)
6491+
_api.check_in_list(['horizontal', 'vertical'], orientation=orientation)
64956492

64966493
if histtype == 'barstacked' and not stacked:
64976494
stacked = True
@@ -7574,7 +7571,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
75747571
"""
75757572
if marker is None and markersize is None and hasattr(Z, 'tocoo'):
75767573
marker = 's'
7577-
cbook._check_in_list(["upper", "lower"], origin=origin)
7574+
_api.check_in_list(["upper", "lower"], origin=origin)
75787575
if marker is None and markersize is None:
75797576
Z = np.asarray(Z)
75807577
mask = np.abs(Z) > precision

lib/matplotlib/axes/_base.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import numpy as np
1212

1313
import matplotlib as mpl
14-
from matplotlib import cbook
14+
from matplotlib import _api, cbook
1515
from matplotlib.cbook import _OrderedSet, _check_1d, index_of
1616
from matplotlib import docstring
1717
import matplotlib.colors as mcolors
@@ -1443,7 +1443,7 @@ def set_adjustable(self, adjustable, share=False):
14431443
which the adjustments for aspect ratios are done sequentially
14441444
and independently on each Axes as it is drawn.
14451445
"""
1446-
cbook._check_in_list(["box", "datalim"], adjustable=adjustable)
1446+
_api.check_in_list(["box", "datalim"], adjustable=adjustable)
14471447
if share:
14481448
axs = {*self._shared_x_axes.get_siblings(self),
14491449
*self._shared_y_axes.get_siblings(self)}
@@ -2941,7 +2941,7 @@ def grid(self, b=None, which='major', axis='both', **kwargs):
29412941
"""
29422942
if len(kwargs):
29432943
b = True
2944-
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
2944+
_api.check_in_list(['x', 'y', 'both'], axis=axis)
29452945
if axis in ['x', 'both']:
29462946
self.xaxis.grid(b, which=which, **kwargs)
29472947
if axis in ['y', 'both']:
@@ -3055,7 +3055,7 @@ def locator_params(self, axis='both', tight=None, **kwargs):
30553055
ax.locator_params(tight=True, nbins=4)
30563056
30573057
"""
3058-
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
3058+
_api.check_in_list(['x', 'y', 'both'], axis=axis)
30593059
update_x = axis in ['x', 'both']
30603060
update_y = axis in ['y', 'both']
30613061
if update_x:
@@ -3129,7 +3129,7 @@ def tick_params(self, axis='both', **kwargs):
31293129
also be red. Gridlines will be red and translucent.
31303130
31313131
"""
3132-
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
3132+
_api.check_in_list(['x', 'y', 'both'], axis=axis)
31333133
if axis in ['x', 'both']:
31343134
xkw = dict(kwargs)
31353135
xkw.pop('left', None)
@@ -3212,7 +3212,7 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
32123212
else:
32133213
loc = (loc if loc is not None
32143214
else mpl.rcParams['xaxis.labellocation'])
3215-
cbook._check_in_list(('left', 'center', 'right'), loc=loc)
3215+
_api.check_in_list(('left', 'center', 'right'), loc=loc)
32163216
if loc == 'left':
32173217
kwargs.update(x=0, horizontalalignment='left')
32183218
elif loc == 'right':
@@ -3555,7 +3555,7 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
35553555
else:
35563556
loc = (loc if loc is not None
35573557
else mpl.rcParams['yaxis.labellocation'])
3558-
cbook._check_in_list(('bottom', 'center', 'top'), loc=loc)
3558+
_api.check_in_list(('bottom', 'center', 'top'), loc=loc)
35593559
if loc == 'bottom':
35603560
kwargs.update(y=0, horizontalalignment='left')
35613561
elif loc == 'top':

lib/matplotlib/axes/_secondary_axes.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import numpy as np
22

3+
from matplotlib import _api
34
import matplotlib.cbook as cbook
45
import matplotlib.docstring as docstring
56
import matplotlib.ticker as mticker
@@ -69,7 +70,7 @@ def set_alignment(self, align):
6970
either 'top' or 'bottom' for orientation='x' or
7071
'left' or 'right' for orientation='y' axis.
7172
"""
72-
cbook._check_in_list(self._locstrings, align=align)
73+
_api.check_in_list(self._locstrings, align=align)
7374
if align == self._locstrings[1]: # Need to change the orientation.
7475
self._locstrings = self._locstrings[::-1]
7576
self.spines[self._locstrings[0]].set_visible(True)

lib/matplotlib/axis.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import numpy as np
1010

1111
import matplotlib as mpl
12+
from matplotlib import _api
1213
import matplotlib.artist as martist
1314
import matplotlib.cbook as cbook
1415
import matplotlib.lines as mlines
@@ -206,7 +207,7 @@ def _set_labelrotation(self, labelrotation):
206207
else:
207208
mode = 'default'
208209
angle = labelrotation
209-
cbook._check_in_list(['auto', 'default'], labelrotation=mode)
210+
_api.check_in_list(['auto', 'default'], labelrotation=mode)
210211
self._labelrotation = (mode, angle)
211212

212213
def apply_tickdir(self, tickdir):
@@ -456,7 +457,7 @@ def apply_tickdir(self, tickdir):
456457
"""Set tick direction. Valid values are 'in', 'out', 'inout'."""
457458
if tickdir is None:
458459
tickdir = mpl.rcParams['%s.direction' % self.__name__.lower()]
459-
cbook._check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
460+
_api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
460461
self._tickdir = tickdir
461462

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

825826
# the kwargs are stored in self._major/minor_tick_kw so that any
@@ -1249,7 +1250,7 @@ def get_ticklabels(self, minor=False, which=None):
12491250
elif which == 'both':
12501251
return self.get_majorticklabels() + self.get_minorticklabels()
12511252
else:
1252-
cbook._check_in_list(['major', 'minor', 'both'], which=which)
1253+
_api.check_in_list(['major', 'minor', 'both'], which=which)
12531254
if minor:
12541255
return self.get_minorticklabels()
12551256
return self.get_majorticklabels()
@@ -1429,7 +1430,7 @@ def grid(self, b=None, which='major', **kwargs):
14291430
'grid will be enabled.')
14301431
b = True
14311432
which = which.lower()
1432-
cbook._check_in_list(['major', 'minor', 'both'], which=which)
1433+
_api.check_in_list(['major', 'minor', 'both'], which=which)
14331434
gridkw = {'grid_' + item[0]: item[1] for item in kwargs.items()}
14341435

14351436
if which in ['minor', 'both']:
@@ -2174,8 +2175,8 @@ def set_ticks_position(self, position):
21742175
can be used if you don't want any ticks. 'none' and 'both'
21752176
affect only the ticks, not the labels.
21762177
"""
2177-
cbook._check_in_list(['top', 'bottom', 'both', 'default', 'none'],
2178-
position=position)
2178+
_api.check_in_list(['top', 'bottom', 'both', 'default', 'none'],
2179+
position=position)
21792180
if position == 'top':
21802181
self.set_tick_params(which='both', top=True, labeltop=True,
21812182
bottom=False, labelbottom=False)
@@ -2461,8 +2462,8 @@ def set_ticks_position(self, position):
24612462
can be used if you don't want any ticks. 'none' and 'both'
24622463
affect only the ticks, not the labels.
24632464
"""
2464-
cbook._check_in_list(['left', 'right', 'both', 'default', 'none'],
2465-
position=position)
2465+
_api.check_in_list(['left', 'right', 'both', 'default', 'none'],
2466+
position=position)
24662467
if position == 'right':
24672468
self.set_tick_params(which='both', right=True, labelright=True,
24682469
left=False, labelleft=False)

lib/matplotlib/backend_bases.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343

4444
import matplotlib as mpl
4545
from matplotlib import (
46-
backend_tools as tools, cbook, colors, textpath, tight_bbox,
46+
_api, backend_tools as tools, cbook, colors, textpath, tight_bbox,
4747
transforms, widgets, get_backend, is_interactive, rcParams)
4848
from matplotlib._pylab_helpers import Gcf
4949
from matplotlib.backend_managers import ToolManager
@@ -914,7 +914,7 @@ def set_antialiased(self, b):
914914

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

920920
def set_clip_rectangle(self, rectangle):
@@ -982,7 +982,7 @@ def set_foreground(self, fg, isRGBA=False):
982982

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

988988
def set_linewidth(self, w):

lib/matplotlib/backends/backend_ps.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import numpy as np
1919

2020
import matplotlib as mpl
21-
from matplotlib import cbook, _path
21+
from matplotlib import _api, cbook, _path
2222
from matplotlib import _text_layout
2323
from matplotlib.afm import AFM
2424
from matplotlib.backend_bases import (
@@ -815,7 +815,7 @@ def _print_ps(
815815
if papertype is None:
816816
papertype = mpl.rcParams['ps.papersize']
817817
papertype = papertype.lower()
818-
cbook._check_in_list(['auto', *papersize], papertype=papertype)
818+
_api.check_in_list(['auto', *papersize], papertype=papertype)
819819

820820
orientation = cbook._check_getitem(
821821
_Orientation, orientation=orientation.lower())

lib/matplotlib/backends/backend_webagg_core.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from PIL import Image
2222
import tornado
2323

24-
from matplotlib import backend_bases, cbook
24+
from matplotlib import _api, backend_bases
2525
from matplotlib.backends import backend_agg
2626
from matplotlib.backend_bases import _Backend
2727

@@ -165,7 +165,7 @@ def set_image_mode(self, mode):
165165
draw this mode may be changed if the resulting image has any
166166
transparent component.
167167
"""
168-
cbook._check_in_list(['full', 'diff'], mode=mode)
168+
_api.check_in_list(['full', 'diff'], mode=mode)
169169
if self._current_image_mode != mode:
170170
self._current_image_mode = mode
171171
self.handle_send_image_mode(None)

0 commit comments

Comments
 (0)