Skip to content

Commit 663358e

Browse files
authored
Merge pull request matplotlib#19244 from timhoffm/move-check_isinstance
Move cbook._check_isinstance() to _api.check_isinstance()
2 parents 3c1d28c + 2d0e0c1 commit 663358e

File tree

21 files changed

+84
-86
lines changed

21 files changed

+84
-86
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: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import logging
2323
from numbers import Integral
2424

25-
from matplotlib import cbook
25+
from matplotlib import _api
2626
from matplotlib.backend_bases import MouseButton
2727
import matplotlib.lines as mlines
2828

@@ -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: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import numpy as np
1919

20-
from matplotlib import cbook, ticker, units
20+
from matplotlib import _api, ticker, units
2121

2222

2323
_log = logging.getLogger(__name__)
@@ -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: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
import numpy as np
3636

3737
import matplotlib as mpl
38-
from matplotlib import _api, cbook, collections, cm, colors, contour, ticker
38+
from matplotlib import _api, collections, cm, colors, contour, ticker
3939
import matplotlib.artist as martist
4040
import matplotlib.patches as mpatches
4141
import matplotlib.path as mpath
@@ -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

0 commit comments

Comments
 (0)