Skip to content

Commit e70c358

Browse files
committed
Move cbook._check_isinstance() to _api.check_isinstance()
1 parent 796dbf4 commit e70c358

21 files changed

+72
-74
lines changed

lib/matplotlib/_api/__init__.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,46 @@ def fget(self):
5757
return self._fget
5858

5959

60+
# In the following check_foo() functions, the first parameter starts with an
61+
# underscore because it is intended to be positional-only (e.g., so that
62+
# `_api.check_isinstance([...], types=foo)` doesn't fail.
63+
64+
def check_isinstance(_types, **kwargs):
65+
"""
66+
For each *key, value* pair in *kwargs*, check that *value* is an instance
67+
of one of *_types*; if not, raise an appropriate TypeError.
68+
69+
As a special case, a ``None`` entry in *_types* is treated as NoneType.
70+
71+
Examples
72+
--------
73+
>>> _api.check_isinstance((SomeClass, None), arg=arg)
74+
"""
75+
types = _types
76+
none_type = type(None)
77+
types = ((types,) if isinstance(types, type) else
78+
(none_type,) if types is None else
79+
tuple(none_type if tp is None else tp for tp in types))
80+
81+
def type_name(tp):
82+
return ("None" if tp is none_type
83+
else tp.__qualname__ if tp.__module__ == "builtins"
84+
else f"{tp.__module__}.{tp.__qualname__}")
85+
86+
for k, v in kwargs.items():
87+
if not isinstance(v, types):
88+
names = [*map(type_name, types)]
89+
if "None" in names: # Move it to the end for better wording.
90+
names.remove("None")
91+
names.append("None")
92+
raise TypeError(
93+
"{!r} must be an instance of {}, not a {}".format(
94+
k,
95+
", ".join(names[:-1]) + " or " + names[-1]
96+
if len(names) > 1 else names[0],
97+
type_name(type(v))))
98+
99+
60100
def check_in_list(_values, *, _print_supported_values=True, **kwargs):
61101
"""
62102
For each *key, value* pair in *kwargs*, check that *value* is in *_values*.

lib/matplotlib/axes/_base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,7 +1075,7 @@ def sharex(self, other):
10751075
axes, and cannot be used if the x-axis is already being shared with
10761076
another axes.
10771077
"""
1078-
cbook._check_isinstance(_AxesBase, other=other)
1078+
_api.check_isinstance(_AxesBase, other=other)
10791079
if self._sharex is not None and other is not self._sharex:
10801080
raise ValueError("x-axis is already shared")
10811081
self._shared_x_axes.join(self, other)
@@ -1094,7 +1094,7 @@ def sharey(self, other):
10941094
axes, and cannot be used if the y-axis is already being shared with
10951095
another axes.
10961096
"""
1097-
cbook._check_isinstance(_AxesBase, other=other)
1097+
_api.check_isinstance(_AxesBase, other=other)
10981098
if self._sharey is not None and other is not self._sharey:
10991099
raise ValueError("y-axis is already shared")
11001100
self._shared_y_axes.join(self, other)

lib/matplotlib/axis.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1599,7 +1599,7 @@ def _set_formatter(self, formatter, level):
15991599
not isinstance(formatter, mticker.TickHelper)):
16001600
formatter = mticker.FuncFormatter(formatter)
16011601
else:
1602-
cbook._check_isinstance(mticker.Formatter, formatter=formatter)
1602+
_api.check_isinstance(mticker.Formatter, formatter=formatter)
16031603

16041604
if (isinstance(formatter, mticker.FixedFormatter)
16051605
and len(formatter.seq) > 0
@@ -1624,7 +1624,7 @@ def set_major_locator(self, locator):
16241624
----------
16251625
locator : `~matplotlib.ticker.Locator`
16261626
"""
1627-
cbook._check_isinstance(mticker.Locator, locator=locator)
1627+
_api.check_isinstance(mticker.Locator, locator=locator)
16281628
self.isDefault_majloc = False
16291629
self.major.locator = locator
16301630
if self.major.formatter:
@@ -1640,7 +1640,7 @@ def set_minor_locator(self, locator):
16401640
----------
16411641
locator : `~matplotlib.ticker.Locator`
16421642
"""
1643-
cbook._check_isinstance(mticker.Locator, locator=locator)
1643+
_api.check_isinstance(mticker.Locator, locator=locator)
16441644
self.isDefault_minloc = False
16451645
self.minor.locator = locator
16461646
if self.minor.formatter:

lib/matplotlib/backend_bases.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -930,7 +930,7 @@ def set_clip_rectangle(self, rectangle):
930930

931931
def set_clip_path(self, path):
932932
"""Set the clip path to a `.TransformedPath` or None."""
933-
cbook._check_isinstance((transforms.TransformedPath, None), path=path)
933+
_api.check_isinstance((transforms.TransformedPath, None), path=path)
934934
self._clippath = path
935935

936936
def set_dashes(self, dash_offset, dash_list):

lib/matplotlib/blocking_input.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def pop_event(self, index=-1):
7878

7979
def __call__(self, n=1, timeout=30):
8080
"""Blocking call to retrieve *n* events."""
81-
cbook._check_isinstance(Integral, n=n)
81+
_api.check_isinstance(Integral, n=n)
8282
self.n = n
8383
self.events = []
8484

lib/matplotlib/category.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ def update(self, data):
217217
convertible = True
218218
for val in OrderedDict.fromkeys(data):
219219
# OrderedDict just iterates over unique values in data.
220-
cbook._check_isinstance((str, bytes), value=val)
220+
_api.check_isinstance((str, bytes), value=val)
221221
if convertible:
222222
# this will only be called so long as convertible is True.
223223
convertible = self._str_is_convertible(val)

lib/matplotlib/cbook/__init__.py

Lines changed: 0 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -2242,47 +2242,6 @@ def _check_and_log_subprocess(command, logger, **kwargs):
22422242
return proc.stdout
22432243

22442244

2245-
# In the following _check_foo functions, the first parameter starts with an
2246-
# underscore because it is intended to be positional-only (e.g., so that
2247-
# `_check_isinstance([...], types=foo)` doesn't fail.
2248-
2249-
2250-
def _check_isinstance(_types, **kwargs):
2251-
"""
2252-
For each *key, value* pair in *kwargs*, check that *value* is an instance
2253-
of one of *_types*; if not, raise an appropriate TypeError.
2254-
2255-
As a special case, a ``None`` entry in *_types* is treated as NoneType.
2256-
2257-
Examples
2258-
--------
2259-
>>> cbook._check_isinstance((SomeClass, None), arg=arg)
2260-
"""
2261-
types = _types
2262-
none_type = type(None)
2263-
types = ((types,) if isinstance(types, type) else
2264-
(none_type,) if types is None else
2265-
tuple(none_type if tp is None else tp for tp in types))
2266-
2267-
def type_name(tp):
2268-
return ("None" if tp is none_type
2269-
else tp.__qualname__ if tp.__module__ == "builtins"
2270-
else f"{tp.__module__}.{tp.__qualname__}")
2271-
2272-
for k, v in kwargs.items():
2273-
if not isinstance(v, types):
2274-
names = [*map(type_name, types)]
2275-
if "None" in names: # Move it to the end for better wording.
2276-
names.remove("None")
2277-
names.append("None")
2278-
raise TypeError(
2279-
"{!r} must be an instance of {}, not a {}".format(
2280-
k,
2281-
", ".join(names[:-1]) + " or " + names[-1]
2282-
if len(names) > 1 else names[0],
2283-
type_name(type(v))))
2284-
2285-
22862245
def _backend_module_name(name):
22872246
"""
22882247
Convert a backend name (either a standard backend -- "Agg", "TkAgg", ... --

lib/matplotlib/cm.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def register_cmap(name=None, cmap=None, *, override_builtin=False):
136136
the registered colormap will be immutable.
137137
138138
"""
139-
cbook._check_isinstance((str, None), name=name)
139+
_api.check_isinstance((str, None), name=name)
140140
if name is None:
141141
try:
142142
name = cmap.name
@@ -448,7 +448,7 @@ def set_norm(self, norm):
448448
the norm of the mappable will reset the norm, locator, and formatters
449449
on the colorbar to default.
450450
"""
451-
cbook._check_isinstance((colors.Normalize, None), norm=norm)
451+
_api.check_isinstance((colors.Normalize, None), norm=norm)
452452
in_init = self.norm is None
453453
if norm is None:
454454
norm = colors.Normalize()

lib/matplotlib/colorbar.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,7 @@ def __init__(self, ax, cmap=None,
429429
extendrect=False,
430430
label='',
431431
):
432-
cbook._check_isinstance([colors.Colormap, None], cmap=cmap)
432+
_api.check_isinstance([colors.Colormap, None], cmap=cmap)
433433
_api.check_in_list(
434434
['vertical', 'horizontal'], orientation=orientation)
435435
_api.check_in_list(

lib/matplotlib/dviread.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,7 @@ class DviFont:
551551
__slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm')
552552

553553
def __init__(self, scale, tfm, texname, vf):
554-
cbook._check_isinstance(bytes, texname=texname)
554+
_api.check_isinstance(bytes, texname=texname)
555555
self._scale = scale
556556
self._tfm = tfm
557557
self.texname = texname

lib/matplotlib/figure.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def add(self, key, a):
122122
"""
123123
# All the error checking may be unnecessary; but this method
124124
# is called so seldom that the overhead is negligible.
125-
cbook._check_isinstance(Axes, a=a)
125+
_api.check_isinstance(Axes, a=a)
126126
try:
127127
hash(key)
128128
except TypeError:

lib/matplotlib/rcsetup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ def validate_color(s):
395395

396396

397397
def _validate_cmap(s):
398-
cbook._check_isinstance((str, Colormap), cmap=s)
398+
_api.check_isinstance((str, Colormap), cmap=s)
399399
return s
400400

401401

@@ -770,7 +770,7 @@ def validate_hatch(s):
770770
"""
771771
if not isinstance(s, str):
772772
raise ValueError("Hatch pattern must be a string")
773-
cbook._check_isinstance(str, hatch_pattern=s)
773+
_api.check_isinstance(str, hatch_pattern=s)
774774
unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'}
775775
if unknown:
776776
raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))

lib/matplotlib/spines.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def __init__(self, axes, spine_type, path, **kwargs):
6969
# non-rectangular axes is currently implemented, and this lets
7070
# them pass through the spines machinery without errors.)
7171
self._position = None
72-
cbook._check_isinstance(matplotlib.path.Path, path=path)
72+
_api.check_isinstance(matplotlib.path.Path, path=path)
7373
self._path = path
7474

7575
# To support drawing both linear and circular spines, this

lib/matplotlib/table.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ def __setitem__(self, position, cell):
342342
"""
343343
Set a custom cell in a given position.
344344
"""
345-
cbook._check_isinstance(Cell, cell=cell)
345+
_api.check_isinstance(Cell, cell=cell)
346346
try:
347347
row, col = position[0], position[1]
348348
except Exception as err:

lib/matplotlib/transforms.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1054,7 +1054,7 @@ def __init__(self, bbox, transform, **kwargs):
10541054
"""
10551055
if not bbox.is_bbox:
10561056
raise ValueError("'bbox' is not a bbox")
1057-
cbook._check_isinstance(Transform, transform=transform)
1057+
_api.check_isinstance(Transform, transform=transform)
10581058
if transform.input_dims != 2 or transform.output_dims != 2:
10591059
raise ValueError(
10601060
"The input and output dimensions of 'transform' must be 2")
@@ -1660,7 +1660,7 @@ def __init__(self, child):
16601660
*child*: A `Transform` instance. This child may later
16611661
be replaced with :meth:`set`.
16621662
"""
1663-
cbook._check_isinstance(Transform, child=child)
1663+
_api.check_isinstance(Transform, child=child)
16641664
self._init(child)
16651665
self.set_children(child)
16661666

@@ -1911,7 +1911,7 @@ def set(self, other):
19111911
Set this transformation from the frozen copy of another
19121912
`Affine2DBase` object.
19131913
"""
1914-
cbook._check_isinstance(Affine2DBase, other=other)
1914+
_api.check_isinstance(Affine2DBase, other=other)
19151915
self._mtx = other.get_matrix()
19161916
self.invalidate()
19171917

@@ -2686,7 +2686,7 @@ def __init__(self, path, transform):
26862686
path : `~.path.Path`
26872687
transform : `Transform`
26882688
"""
2689-
cbook._check_isinstance(Transform, transform=transform)
2689+
_api.check_isinstance(Transform, transform=transform)
26902690
super().__init__()
26912691
self._path = path
26922692
self._transform = transform

lib/matplotlib/tri/trifinder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class TriFinder:
1717
"""
1818

1919
def __init__(self, triangulation):
20-
cbook._check_isinstance(Triangulation, triangulation=triangulation)
20+
_api.check_isinstance(Triangulation, triangulation=triangulation)
2121
self._triangulation = triangulation
2222

2323

lib/matplotlib/tri/triinterpolate.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,15 @@ class TriInterpolator:
3131
"""
3232

3333
def __init__(self, triangulation, z, trifinder=None):
34-
cbook._check_isinstance(Triangulation, triangulation=triangulation)
34+
_api.check_isinstance(Triangulation, triangulation=triangulation)
3535
self._triangulation = triangulation
3636

3737
self._z = np.asarray(z)
3838
if self._z.shape != self._triangulation.x.shape:
3939
raise ValueError("z array must have same length as triangulation x"
4040
" and y arrays")
4141

42-
cbook._check_isinstance((TriFinder, None), trifinder=trifinder)
42+
_api.check_isinstance((TriFinder, None), trifinder=trifinder)
4343
self._trifinder = trifinder or self._triangulation.get_trifinder()
4444

4545
# Default scaling factors : 1.0 (= no scaling)
@@ -996,8 +996,7 @@ class _DOF_estimator:
996996
gradient coordinates.
997997
"""
998998
def __init__(self, interpolator, **kwargs):
999-
cbook._check_isinstance(
1000-
CubicTriInterpolator, interpolator=interpolator)
999+
_api.check_isinstance(CubicTriInterpolator, interpolator=interpolator)
10011000
self._pts = interpolator._pts
10021001
self._tris_pts = interpolator._tris_pts
10031002
self.z = interpolator._z

lib/matplotlib/tri/tripcolor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None,
114114

115115
collection.set_alpha(alpha)
116116
collection.set_array(C)
117-
cbook._check_isinstance((Normalize, None), norm=norm)
117+
_api.check_isinstance((Normalize, None), norm=norm)
118118
collection.set_cmap(cmap)
119119
collection.set_norm(norm)
120120
collection._scale_norm(norm, vmin, vmax)

lib/matplotlib/tri/trirefine.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class TriRefiner:
4040
"""
4141

4242
def __init__(self, triangulation):
43-
cbook._check_isinstance(Triangulation, triangulation=triangulation)
43+
_api.check_isinstance(Triangulation, triangulation=triangulation)
4444
self._triangulation = triangulation
4545

4646

@@ -158,8 +158,8 @@ def refine_field(self, z, triinterpolator=None, subdiv=3):
158158
interp = matplotlib.tri.CubicTriInterpolator(
159159
self._triangulation, z)
160160
else:
161-
cbook._check_isinstance(matplotlib.tri.TriInterpolator,
162-
triinterpolator=triinterpolator)
161+
_api.check_isinstance(matplotlib.tri.TriInterpolator,
162+
triinterpolator=triinterpolator)
163163
interp = triinterpolator
164164

165165
refi_tri, found_index = self.refine_triangulation(

lib/matplotlib/tri/tritools.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class TriAnalyzer:
2626
"""
2727

2828
def __init__(self, triangulation):
29-
cbook._check_isinstance(Triangulation, triangulation=triangulation)
29+
_api.check_isinstance(Triangulation, triangulation=triangulation)
3030
self._triangulation = triangulation
3131

3232
@property

lib/mpl_toolkits/axes_grid1/axes_size.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ class Fixed(_Base):
5454
"""
5555

5656
def __init__(self, fixed_size):
57-
cbook._check_isinstance(Number, fixed_size=fixed_size)
57+
_api.check_isinstance(Number, fixed_size=fixed_size)
5858
self.fixed_size = fixed_size
5959

6060
def get_size(self, renderer):
@@ -189,7 +189,7 @@ class Fraction(_Base):
189189
"""
190190

191191
def __init__(self, fraction, ref_size):
192-
cbook._check_isinstance(Number, fraction=fraction)
192+
_api.check_isinstance(Number, fraction=fraction)
193193
self._fraction_ref = ref_size
194194
self._fraction = fraction
195195

0 commit comments

Comments
 (0)