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

Skip to content

Private api2 #18512

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 2 commits into from
Sep 18, 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
62 changes: 62 additions & 0 deletions lib/matplotlib/_api.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import itertools


def check_in_list(_values, *, _print_supported_values=True, **kwargs):
Expand Down Expand Up @@ -31,3 +32,64 @@ def check_in_list(_values, *, _print_supported_values=True, **kwargs):
f"supported values are {', '.join(map(repr, values))}")
else:
raise ValueError(f"{val!r} is not a valid value for {key}")


def check_shape(_shape, **kwargs):
"""
For each *key, value* pair in *kwargs*, check that *value* has the shape
*_shape*, if not, raise an appropriate ValueError.

*None* in the shape is treated as a "free" size that can have any length.
e.g. (None, 2) -> (N, 2)

The values checked must be numpy arrays.

Examples
--------
To check for (N, 2) shaped arrays

>>> _api.check_shape((None, 2), arg=arg, other_arg=other_arg)
"""
target_shape = _shape
for k, v in kwargs.items():
data_shape = v.shape

if len(target_shape) != len(data_shape) or any(
t not in [s, None]
for t, s in zip(target_shape, data_shape)
):
dim_labels = iter(itertools.chain(
'MNLIJKLH',
(f"D{i}" for i in itertools.count())))
text_shape = ", ".join((str(n)
if n is not None
else next(dim_labels)
for n in target_shape))

raise ValueError(
f"{k!r} must be {len(target_shape)}D "
f"with shape ({text_shape}). "
f"Your input has shape {v.shape}."
)


def check_getitem(_mapping, **kwargs):
"""
*kwargs* must consist of a single *key, value* pair. If *key* is in
*_mapping*, return ``_mapping[value]``; else, raise an appropriate
ValueError.

Examples
--------
>>> _api.check_getitem({"foo": "bar"}, arg=arg)
"""
mapping = _mapping
if len(kwargs) != 1:
raise ValueError("check_getitem takes a single keyword argument")
(k, v), = kwargs.items()
try:
return mapping[v]
except KeyError:
raise ValueError(
"{!r} is not a valid value for {}; supported values are {}"
.format(v, k, ', '.join(map(repr, mapping)))) from None
6 changes: 3 additions & 3 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def get_title(self, loc="center"):
titles = {'left': self._left_title,
'center': self.title,
'right': self._right_title}
title = cbook._check_getitem(titles, loc=loc.lower())
title = _api.check_getitem(titles, loc=loc.lower())
return title.get_text()

def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
Expand Down Expand Up @@ -149,7 +149,7 @@ def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
titles = {'left': self._left_title,
'center': self.title,
'right': self._right_title}
title = cbook._check_getitem(titles, loc=loc.lower())
title = _api.check_getitem(titles, loc=loc.lower())
default = {
'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
Expand Down Expand Up @@ -7195,7 +7195,7 @@ def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
pad_to=pad_to, sides=sides)
freqs += Fc

yunits = cbook._check_getitem(
yunits = _api.check_getitem(
{None: 'energy', 'default': 'energy', 'linear': 'energy',
'dB': 'dB'},
scale=scale)
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3002,10 +3002,10 @@ def ticklabel_format(self, *, axis='both', style='', scilimits=None,
raise ValueError("scilimits must be a sequence of 2 integers"
) from err
STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None}
is_sci_style = cbook._check_getitem(STYLES, style=style)
is_sci_style = _api.check_getitem(STYLES, style=style)
axis_map = {**{k: [v] for k, v in self._get_axis_map().items()},
'both': self._get_axis_list()}
axises = cbook._check_getitem(axis_map, axis=axis)
axises = _api.check_getitem(axis_map, axis=axis)
try:
for axis in axises:
if is_sci_style is not None:
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -2048,7 +2048,7 @@ def set_label_position(self, position):
----------
position : {'top', 'bottom'}
"""
self.label.set_verticalalignment(cbook._check_getitem({
self.label.set_verticalalignment(_api.check_getitem({
'top': 'baseline', 'bottom': 'top',
}, position=position))
self.label_position = position
Expand Down Expand Up @@ -2340,7 +2340,7 @@ def set_label_position(self, position):
"""
self.label.set_rotation_mode('anchor')
self.label.set_horizontalalignment('center')
self.label.set_verticalalignment(cbook._check_getitem({
self.label.set_verticalalignment(_api.check_getitem({
'left': 'bottom', 'right': 'top',
}, position=position))
self.label_position = position
Expand Down Expand Up @@ -2425,7 +2425,7 @@ def set_offset_position(self, position):
position : {'left', 'right'}
"""
x, y = self.offsetText.get_position()
x = cbook._check_getitem({'left': 0, 'right': 1}, position=position)
x = _api.check_getitem({'left': 0, 'right': 1}, position=position)

self.offsetText.set_ha(position)
self.offsetText.set_position((x, y))
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/backends/backend_cairo.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"cairo backend requires that pycairo>=1.11.0 or cairocffi "
"is installed") from err

from .. import cbook, font_manager
from .. import _api, cbook, font_manager
from matplotlib.backend_bases import (
_Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
GraphicsContextBase, RendererBase)
Expand Down Expand Up @@ -358,7 +358,7 @@ def set_alpha(self, alpha):
# one for False.

def set_capstyle(self, cs):
self.ctx.set_line_cap(cbook._check_getitem(self._capd, capstyle=cs))
self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs))
self._capstyle = cs

def set_clip_rectangle(self, rectangle):
Expand Down Expand Up @@ -401,7 +401,7 @@ def get_rgb(self):
return self.ctx.get_source().get_rgba()[:3]

def set_joinstyle(self, js):
self.ctx.set_line_join(cbook._check_getitem(self._joind, joinstyle=js))
self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js))
self._joinstyle = js

def set_linewidth(self, w):
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,7 +817,7 @@ def _print_ps(
papertype = papertype.lower()
_api.check_in_list(['auto', *papersize], papertype=papertype)

orientation = cbook._check_getitem(
orientation = _api.check_getitem(
_Orientation, orientation=orientation.lower())

printer = (self._print_figure_tex
Expand Down
61 changes: 0 additions & 61 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2281,67 +2281,6 @@ def type_name(tp):
type_name(type(v))))


def _check_shape(_shape, **kwargs):
"""
For each *key, value* pair in *kwargs*, check that *value* has the shape
*_shape*, if not, raise an appropriate ValueError.

*None* in the shape is treated as a "free" size that can have any length.
e.g. (None, 2) -> (N, 2)

The values checked must be numpy arrays.

Examples
--------
To check for (N, 2) shaped arrays

>>> _api.check_in_list((None, 2), arg=arg, other_arg=other_arg)
"""
target_shape = _shape
for k, v in kwargs.items():
data_shape = v.shape

if len(target_shape) != len(data_shape) or any(
t not in [s, None]
for t, s in zip(target_shape, data_shape)
):
dim_labels = iter(itertools.chain(
'MNLIJKLH',
(f"D{i}" for i in itertools.count())))
text_shape = ", ".join((str(n)
if n is not None
else next(dim_labels)
for n in target_shape))

raise ValueError(
f"{k!r} must be {len(target_shape)}D "
f"with shape ({text_shape}). "
f"Your input has shape {v.shape}."
)


def _check_getitem(_mapping, **kwargs):
"""
*kwargs* must consist of a single *key, value* pair. If *key* is in
*_mapping*, return ``_mapping[value]``; else, raise an appropriate
ValueError.

Examples
--------
>>> cbook._check_getitem({"foo": "bar"}, arg=arg)
"""
mapping = _mapping
if len(kwargs) != 1:
raise ValueError("_check_getitem takes a single keyword argument")
(k, v), = kwargs.items()
try:
return mapping[v]
except KeyError:
raise ValueError(
"{!r} is not a valid value for {}; supported values are {}"
.format(v, k, ', '.join(map(repr, mapping)))) from None


class _classproperty:
"""
Like `property`, but also triggers on access via the class, and it is the
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -1619,7 +1619,7 @@ def set_orientation(self, orientation=None):
orientation : {'horizontal', 'vertical'}
"""
try:
is_horizontal = cbook._check_getitem(
is_horizontal = _api.check_getitem(
{"horizontal": True, "vertical": False},
orientation=orientation)
except ValueError:
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ def __init__(self, ax, cmap=None,
self.values = values
self.boundaries = boundaries
self.extend = extend
self._inside = cbook._check_getitem(
self._inside = _api.check_getitem(
{'neither': slice(0, None), 'both': slice(1, -1),
'min': slice(1, None), 'max': slice(0, -1)},
extend=extend)
Expand Down Expand Up @@ -1372,10 +1372,10 @@ def remove(self):

def _normalize_location_orientation(location, orientation):
if location is None:
location = cbook._check_getitem(
location = _api.check_getitem(
{None: "right", "vertical": "right", "horizontal": "bottom"},
orientation=orientation)
loc_settings = cbook._check_getitem({
loc_settings = _api.check_getitem({
"left": {"location": "left", "orientation": "vertical",
"anchor": (1.0, 0.5), "panchor": (0.0, 0.5), "pad": 0.10},
"right": {"location": "right", "orientation": "vertical",
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import numpy as np
from PIL import Image

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

fontset_class = (
_mathtext.StandardPsFonts if force_standard_ps_fonts
else cbook._check_getitem(
else _api.check_getitem(
self._font_type_mapping, fontset=prop.get_math_fontfamily()))
backend = self._backend_mapping[self._output]()
font_output = fontset_class(prop, backend)
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/offsetbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -1095,7 +1095,7 @@ def __init__(self, loc,
self.set_child(child)

if isinstance(loc, str):
loc = cbook._check_getitem(self.codes, loc=loc)
loc = _api.check_getitem(self.codes, loc=loc)

self.loc = loc
self.borderpad = borderpad
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import numpy as np

import matplotlib as mpl
from . import _path, cbook
from . import _api, _path, cbook
from .cbook import _to_unmasked_float_array, simple_linear_interpolation
from .bezier import BezierSegment

Expand Down Expand Up @@ -129,7 +129,7 @@ def __init__(self, vertices, codes=None, _interpolation_steps=1,
and codes as read-only arrays.
"""
vertices = _to_unmasked_float_array(vertices)
cbook._check_shape((None, 2), vertices=vertices)
_api.check_shape((None, 2), vertices=vertices)

if codes is not None:
codes = np.asarray(codes, self.code_type)
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def draw(self, renderer):
self.stale = False

def _set_transform(self):
self.set_transform(cbook._check_getitem({
self.set_transform(_api.check_getitem({
"data": self.Q.axes.transData,
"axes": self.Q.axes.transAxes,
"figure": self.Q.axes.figure.transFigure,
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def __init__(self, base, nonpositive='clip'):
if base <= 0 or base == 1:
raise ValueError('The log base cannot be <= 0 or == 1')
self.base = base
self._clip = cbook._check_getitem(
self._clip = _api.check_getitem(
{"clip": True, "mask": False}, nonpositive=nonpositive)

def __str__(self):
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/testing/jpl_units/UnitDbl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import operator

from matplotlib import cbook
from matplotlib import _api


class UnitDbl:
Expand Down Expand Up @@ -48,7 +48,7 @@ def __init__(self, value, units):
- value The numeric value of the UnitDbl.
- units The string name of the units the value is in.
"""
data = cbook._check_getitem(self.allowed, units=units)
data = _api.check_getitem(self.allowed, units=units)
self._value = float(value * data[0])
self._units = data[1]

Expand All @@ -68,7 +68,7 @@ def convert(self, units):
"""
if self._units == units:
return self._value
data = cbook._check_getitem(self.allowed, units=units)
data = _api.check_getitem(self.allowed, units=units)
if self._units != data[1]:
raise ValueError(f"Error trying to convert to different units.\n"
f" Invalid conversion requested.\n"
Expand Down
21 changes: 21 additions & 0 deletions lib/matplotlib/tests/test_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import re

import numpy as np
import pytest

from matplotlib import _api


@pytest.mark.parametrize('target,test_shape',
[((None, ), (1, 3)),
((None, 3), (1,)),
((None, 3), (1, 2)),
((1, 5), (1, 9)),
((None, 2, None), (1, 3, 1))
])
def test_check_shape(target, test_shape):
error_pattern = (f"^'aardvark' must be {len(target)}D.*" +
re.escape(f'has shape {test_shape}'))
data = np.zeros(test_shape)
with pytest.raises(ValueError, match=error_pattern):
_api.check_shape(target, aardvark=data)
Loading