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

Skip to content

Commit 986bbfe

Browse files
authored
Merge pull request #18512 from timhoffm/private-api2
Private api2
2 parents 8349677 + c725179 commit 986bbfe

File tree

19 files changed

+115
-110
lines changed

19 files changed

+115
-110
lines changed

lib/matplotlib/_api.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import itertools
12

23

34
def check_in_list(_values, *, _print_supported_values=True, **kwargs):
@@ -31,3 +32,64 @@ def check_in_list(_values, *, _print_supported_values=True, **kwargs):
3132
f"supported values are {', '.join(map(repr, values))}")
3233
else:
3334
raise ValueError(f"{val!r} is not a valid value for {key}")
35+
36+
37+
def check_shape(_shape, **kwargs):
38+
"""
39+
For each *key, value* pair in *kwargs*, check that *value* has the shape
40+
*_shape*, if not, raise an appropriate ValueError.
41+
42+
*None* in the shape is treated as a "free" size that can have any length.
43+
e.g. (None, 2) -> (N, 2)
44+
45+
The values checked must be numpy arrays.
46+
47+
Examples
48+
--------
49+
To check for (N, 2) shaped arrays
50+
51+
>>> _api.check_shape((None, 2), arg=arg, other_arg=other_arg)
52+
"""
53+
target_shape = _shape
54+
for k, v in kwargs.items():
55+
data_shape = v.shape
56+
57+
if len(target_shape) != len(data_shape) or any(
58+
t not in [s, None]
59+
for t, s in zip(target_shape, data_shape)
60+
):
61+
dim_labels = iter(itertools.chain(
62+
'MNLIJKLH',
63+
(f"D{i}" for i in itertools.count())))
64+
text_shape = ", ".join((str(n)
65+
if n is not None
66+
else next(dim_labels)
67+
for n in target_shape))
68+
69+
raise ValueError(
70+
f"{k!r} must be {len(target_shape)}D "
71+
f"with shape ({text_shape}). "
72+
f"Your input has shape {v.shape}."
73+
)
74+
75+
76+
def check_getitem(_mapping, **kwargs):
77+
"""
78+
*kwargs* must consist of a single *key, value* pair. If *key* is in
79+
*_mapping*, return ``_mapping[value]``; else, raise an appropriate
80+
ValueError.
81+
82+
Examples
83+
--------
84+
>>> _api.check_getitem({"foo": "bar"}, arg=arg)
85+
"""
86+
mapping = _mapping
87+
if len(kwargs) != 1:
88+
raise ValueError("check_getitem takes a single keyword argument")
89+
(k, v), = kwargs.items()
90+
try:
91+
return mapping[v]
92+
except KeyError:
93+
raise ValueError(
94+
"{!r} is not a valid value for {}; supported values are {}"
95+
.format(v, k, ', '.join(map(repr, mapping)))) from None

lib/matplotlib/axes/_axes.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def get_title(self, loc="center"):
8686
titles = {'left': self._left_title,
8787
'center': self.title,
8888
'right': self._right_title}
89-
title = cbook._check_getitem(titles, loc=loc.lower())
89+
title = _api.check_getitem(titles, loc=loc.lower())
9090
return title.get_text()
9191

9292
def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
@@ -149,7 +149,7 @@ def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
149149
titles = {'left': self._left_title,
150150
'center': self.title,
151151
'right': self._right_title}
152-
title = cbook._check_getitem(titles, loc=loc.lower())
152+
title = _api.check_getitem(titles, loc=loc.lower())
153153
default = {
154154
'fontsize': rcParams['axes.titlesize'],
155155
'fontweight': rcParams['axes.titleweight'],
@@ -7195,7 +7195,7 @@ def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
71957195
pad_to=pad_to, sides=sides)
71967196
freqs += Fc
71977197

7198-
yunits = cbook._check_getitem(
7198+
yunits = _api.check_getitem(
71997199
{None: 'energy', 'default': 'energy', 'linear': 'energy',
72007200
'dB': 'dB'},
72017201
scale=scale)

lib/matplotlib/axes/_base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3002,10 +3002,10 @@ def ticklabel_format(self, *, axis='both', style='', scilimits=None,
30023002
raise ValueError("scilimits must be a sequence of 2 integers"
30033003
) from err
30043004
STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None}
3005-
is_sci_style = cbook._check_getitem(STYLES, style=style)
3005+
is_sci_style = _api.check_getitem(STYLES, style=style)
30063006
axis_map = {**{k: [v] for k, v in self._get_axis_map().items()},
30073007
'both': self._get_axis_list()}
3008-
axises = cbook._check_getitem(axis_map, axis=axis)
3008+
axises = _api.check_getitem(axis_map, axis=axis)
30093009
try:
30103010
for axis in axises:
30113011
if is_sci_style is not None:

lib/matplotlib/axis.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2048,7 +2048,7 @@ def set_label_position(self, position):
20482048
----------
20492049
position : {'top', 'bottom'}
20502050
"""
2051-
self.label.set_verticalalignment(cbook._check_getitem({
2051+
self.label.set_verticalalignment(_api.check_getitem({
20522052
'top': 'baseline', 'bottom': 'top',
20532053
}, position=position))
20542054
self.label_position = position
@@ -2340,7 +2340,7 @@ def set_label_position(self, position):
23402340
"""
23412341
self.label.set_rotation_mode('anchor')
23422342
self.label.set_horizontalalignment('center')
2343-
self.label.set_verticalalignment(cbook._check_getitem({
2343+
self.label.set_verticalalignment(_api.check_getitem({
23442344
'left': 'bottom', 'right': 'top',
23452345
}, position=position))
23462346
self.label_position = position
@@ -2425,7 +2425,7 @@ def set_offset_position(self, position):
24252425
position : {'left', 'right'}
24262426
"""
24272427
x, y = self.offsetText.get_position()
2428-
x = cbook._check_getitem({'left': 0, 'right': 1}, position=position)
2428+
x = _api.check_getitem({'left': 0, 'right': 1}, position=position)
24292429

24302430
self.offsetText.set_ha(position)
24312431
self.offsetText.set_position((x, y))

lib/matplotlib/backends/backend_cairo.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
"cairo backend requires that pycairo>=1.11.0 or cairocffi "
2525
"is installed") from err
2626

27-
from .. import cbook, font_manager
27+
from .. import _api, cbook, font_manager
2828
from matplotlib.backend_bases import (
2929
_Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
3030
GraphicsContextBase, RendererBase)
@@ -358,7 +358,7 @@ def set_alpha(self, alpha):
358358
# one for False.
359359

360360
def set_capstyle(self, cs):
361-
self.ctx.set_line_cap(cbook._check_getitem(self._capd, capstyle=cs))
361+
self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs))
362362
self._capstyle = cs
363363

364364
def set_clip_rectangle(self, rectangle):
@@ -401,7 +401,7 @@ def get_rgb(self):
401401
return self.ctx.get_source().get_rgba()[:3]
402402

403403
def set_joinstyle(self, js):
404-
self.ctx.set_line_join(cbook._check_getitem(self._joind, joinstyle=js))
404+
self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js))
405405
self._joinstyle = js
406406

407407
def set_linewidth(self, w):

lib/matplotlib/backends/backend_ps.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -816,7 +816,7 @@ def _print_ps(
816816
papertype = papertype.lower()
817817
_api.check_in_list(['auto', *papersize], papertype=papertype)
818818

819-
orientation = cbook._check_getitem(
819+
orientation = _api.check_getitem(
820820
_Orientation, orientation=orientation.lower())
821821

822822
printer = (self._print_figure_tex

lib/matplotlib/cbook/__init__.py

Lines changed: 0 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -2281,67 +2281,6 @@ def type_name(tp):
22812281
type_name(type(v))))
22822282

22832283

2284-
def _check_shape(_shape, **kwargs):
2285-
"""
2286-
For each *key, value* pair in *kwargs*, check that *value* has the shape
2287-
*_shape*, if not, raise an appropriate ValueError.
2288-
2289-
*None* in the shape is treated as a "free" size that can have any length.
2290-
e.g. (None, 2) -> (N, 2)
2291-
2292-
The values checked must be numpy arrays.
2293-
2294-
Examples
2295-
--------
2296-
To check for (N, 2) shaped arrays
2297-
2298-
>>> _api.check_in_list((None, 2), arg=arg, other_arg=other_arg)
2299-
"""
2300-
target_shape = _shape
2301-
for k, v in kwargs.items():
2302-
data_shape = v.shape
2303-
2304-
if len(target_shape) != len(data_shape) or any(
2305-
t not in [s, None]
2306-
for t, s in zip(target_shape, data_shape)
2307-
):
2308-
dim_labels = iter(itertools.chain(
2309-
'MNLIJKLH',
2310-
(f"D{i}" for i in itertools.count())))
2311-
text_shape = ", ".join((str(n)
2312-
if n is not None
2313-
else next(dim_labels)
2314-
for n in target_shape))
2315-
2316-
raise ValueError(
2317-
f"{k!r} must be {len(target_shape)}D "
2318-
f"with shape ({text_shape}). "
2319-
f"Your input has shape {v.shape}."
2320-
)
2321-
2322-
2323-
def _check_getitem(_mapping, **kwargs):
2324-
"""
2325-
*kwargs* must consist of a single *key, value* pair. If *key* is in
2326-
*_mapping*, return ``_mapping[value]``; else, raise an appropriate
2327-
ValueError.
2328-
2329-
Examples
2330-
--------
2331-
>>> cbook._check_getitem({"foo": "bar"}, arg=arg)
2332-
"""
2333-
mapping = _mapping
2334-
if len(kwargs) != 1:
2335-
raise ValueError("_check_getitem takes a single keyword argument")
2336-
(k, v), = kwargs.items()
2337-
try:
2338-
return mapping[v]
2339-
except KeyError:
2340-
raise ValueError(
2341-
"{!r} is not a valid value for {}; supported values are {}"
2342-
.format(v, k, ', '.join(map(repr, mapping)))) from None
2343-
2344-
23452284
class _classproperty:
23462285
"""
23472286
Like `property`, but also triggers on access via the class, and it is the

lib/matplotlib/collections.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1619,7 +1619,7 @@ def set_orientation(self, orientation=None):
16191619
orientation : {'horizontal', 'vertical'}
16201620
"""
16211621
try:
1622-
is_horizontal = cbook._check_getitem(
1622+
is_horizontal = _api.check_getitem(
16231623
{"horizontal": True, "vertical": False},
16241624
orientation=orientation)
16251625
except ValueError:

lib/matplotlib/colorbar.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,7 @@ def __init__(self, ax, cmap=None,
461461
self.values = values
462462
self.boundaries = boundaries
463463
self.extend = extend
464-
self._inside = cbook._check_getitem(
464+
self._inside = _api.check_getitem(
465465
{'neither': slice(0, None), 'both': slice(1, -1),
466466
'min': slice(1, None), 'max': slice(0, -1)},
467467
extend=extend)
@@ -1372,10 +1372,10 @@ def remove(self):
13721372

13731373
def _normalize_location_orientation(location, orientation):
13741374
if location is None:
1375-
location = cbook._check_getitem(
1375+
location = _api.check_getitem(
13761376
{None: "right", "vertical": "right", "horizontal": "bottom"},
13771377
orientation=orientation)
1378-
loc_settings = cbook._check_getitem({
1378+
loc_settings = _api.check_getitem({
13791379
"left": {"location": "left", "orientation": "vertical",
13801380
"anchor": (1.0, 0.5), "panchor": (0.0, 0.5), "pad": 0.10},
13811381
"right": {"location": "right", "orientation": "vertical",

lib/matplotlib/mathtext.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import numpy as np
2525
from PIL import Image
2626

27-
from matplotlib import cbook, colors as mcolors, rcParams, _mathtext
27+
from matplotlib import _api, cbook, colors as mcolors, rcParams, _mathtext
2828
from matplotlib.ft2font import FT2Image, LOAD_NO_HINTING
2929
from matplotlib.font_manager import FontProperties
3030
# Backcompat imports, all are deprecated as of 3.4.
@@ -444,7 +444,7 @@ def _parse_cached(self, s, dpi, prop, force_standard_ps_fonts):
444444

445445
fontset_class = (
446446
_mathtext.StandardPsFonts if force_standard_ps_fonts
447-
else cbook._check_getitem(
447+
else _api.check_getitem(
448448
self._font_type_mapping, fontset=prop.get_math_fontfamily()))
449449
backend = self._backend_mapping[self._output]()
450450
font_output = fontset_class(prop, backend)

0 commit comments

Comments
 (0)