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

Skip to content

Commit 08bff55

Browse files
committed
Add a _check_getitem helper to go with _check_in_list/_check_isinstance.
Also rename the first parameter of these helpers to start with an underscore, to mark them as effectively positional-only.
1 parent 362ce4a commit 08bff55

File tree

9 files changed

+60
-49
lines changed

9 files changed

+60
-49
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,7 @@ def get_title(self, loc="center"):
141141
titles = {'left': self._left_title,
142142
'center': self.title,
143143
'right': self._right_title}
144-
cbook._check_in_list(titles, loc=loc.lower())
145-
title = titles[loc.lower()]
144+
title = cbook._check_getitem(titles, loc=loc.lower())
146145
return title.get_text()
147146

148147
def set_title(self, label, fontdict=None, loc=None, pad=None,
@@ -193,8 +192,7 @@ def set_title(self, label, fontdict=None, loc=None, pad=None,
193192
titles = {'left': self._left_title,
194193
'center': self.title,
195194
'right': self._right_title}
196-
cbook._check_in_list(titles, loc=loc.lower())
197-
title = titles[loc.lower()]
195+
title = cbook._check_getitem(titles, loc=loc.lower())
198196
default = {
199197
'fontsize': rcParams['axes.titlesize'],
200198
'fontweight': rcParams['axes.titleweight'],

lib/matplotlib/axis.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1987,12 +1987,9 @@ def set_label_position(self, position):
19871987
----------
19881988
position : {'top', 'bottom'}
19891989
"""
1990-
if position == 'top':
1991-
self.label.set_verticalalignment('baseline')
1992-
elif position == 'bottom':
1993-
self.label.set_verticalalignment('top')
1994-
else:
1995-
raise ValueError("Position accepts only 'top' or 'bottom'")
1990+
self.label.set_verticalalignment(cbook._check_getitem({
1991+
'top': 'baseline', 'bottom': 'top',
1992+
}, position=position))
19961993
self.label_position = position
19971994
self.stale = True
19981995

@@ -2281,12 +2278,9 @@ def set_label_position(self, position):
22812278
"""
22822279
self.label.set_rotation_mode('anchor')
22832280
self.label.set_horizontalalignment('center')
2284-
if position == 'left':
2285-
self.label.set_verticalalignment('bottom')
2286-
elif position == 'right':
2287-
self.label.set_verticalalignment('top')
2288-
else:
2289-
raise ValueError("Position accepts only 'left' or 'right'")
2281+
self.label.set_verticalalignment(cbook._check_getitem({
2282+
'left': 'bottom', 'right': 'top',
2283+
}, position=position))
22902284
self.label_position = position
22912285
self.stale = True
22922286

lib/matplotlib/backends/backend_cairo.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -338,9 +338,8 @@ def set_alpha(self, alpha):
338338
# one for False.
339339

340340
def set_capstyle(self, cs):
341-
cbook._check_in_list(('butt', 'round', 'projecting'), capstyle=cs)
341+
self.ctx.set_line_cap(cbook._check_getitem(self._capd, capstyle=cs))
342342
self._capstyle = cs
343-
self.ctx.set_line_cap(self._capd[cs])
344343

345344
def set_clip_rectangle(self, rectangle):
346345
if not rectangle:
@@ -382,9 +381,8 @@ def get_rgb(self):
382381
return self.ctx.get_source().get_rgba()[:3]
383382

384383
def set_joinstyle(self, js):
385-
cbook._check_in_list(('miter', 'round', 'bevel'), joinstyle=js)
384+
self.ctx.set_line_join(cbook._check_getitem(self._joind, joinstyle=js))
386385
self._joinstyle = js
387-
self.ctx.set_line_join(self._joind[js])
388386

389387
def set_linewidth(self, w):
390388
self._linewidth = float(w)

lib/matplotlib/cbook/__init__.py

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2050,17 +2050,23 @@ def _check_and_log_subprocess(command, logger, **kwargs):
20502050
return report
20512051

20522052

2053-
def _check_isinstance(types, **kwargs):
2053+
# In the following _check_foo functions, the first parameter starts with an
2054+
# underscore because it is intended to be positional-only (e.g., so that
2055+
# `_check_isinstance([...], types=foo)` doesn't fail.
2056+
2057+
2058+
def _check_isinstance(_types, **kwargs):
20542059
"""
20552060
For each *key, value* pair in *kwargs*, check that *value* is an instance
2056-
of one of *types*; if not, raise an appropriate TypeError.
2061+
of one of *_types*; if not, raise an appropriate TypeError.
20572062
2058-
As a special case, a ``None`` entry in *types* is treated as NoneType.
2063+
As a special case, a ``None`` entry in *_types* is treated as NoneType.
20592064
20602065
Examples
20612066
--------
20622067
>>> cbook._check_isinstance((SomeClass, None), arg=arg)
20632068
"""
2069+
types = _types
20642070
if isinstance(types, type) or types is None:
20652071
types = (types,)
20662072
none_allowed = None in types
@@ -2084,17 +2090,40 @@ def type_name(tp):
20842090
type_name(type(v))))
20852091

20862092

2087-
def _check_in_list(values, **kwargs):
2093+
def _check_in_list(_values, **kwargs):
20882094
"""
2089-
For each *key, value* pair in *kwargs*, check that *value* is in *values*;
2095+
For each *key, value* pair in *kwargs*, check that *value* is in *_values*;
20902096
if not, raise an appropriate ValueError.
20912097
20922098
Examples
20932099
--------
20942100
>>> cbook._check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg)
20952101
"""
2102+
values = _values
20962103
for k, v in kwargs.items():
20972104
if v not in values:
20982105
raise ValueError(
20992106
"{!r} is not a valid value for {}; supported values are {}"
21002107
.format(v, k, ', '.join(map(repr, values))))
2108+
2109+
2110+
def _check_getitem(_mapping, **kwargs):
2111+
"""
2112+
*kwargs* must consist of a single *key, value* pair. If *key* is in
2113+
*_mapping*, return ``_mapping[value]``; else, raise an appropriate
2114+
ValueError.
2115+
2116+
Examples
2117+
--------
2118+
>>> cbook._check_getitem({"foo": "bar"}, arg=arg)
2119+
"""
2120+
mapping = _mapping
2121+
if len(kwargs) != 1:
2122+
raise ValueError("_check_getitem takes a single keyword argument")
2123+
(k, v), = kwargs.items()
2124+
try:
2125+
return mapping[v]
2126+
except KeyError:
2127+
raise ValueError(
2128+
"{!r} is not a valid value for {}; supported values are {}"
2129+
.format(v, k, ', '.join(map(repr, mapping)))) from None

lib/matplotlib/mathtext.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3340,8 +3340,8 @@ def parse(self, s, dpi = 72, prop = None):
33403340
else:
33413341
backend = self._backend_mapping[self._output]()
33423342
fontset = rcParams['mathtext.fontset'].lower()
3343-
cbook._check_in_list(self._font_type_mapping, fontset=fontset)
3344-
fontset_class = self._font_type_mapping[fontset]
3343+
fontset_class = cbook._check_getitem(
3344+
self._font_type_mapping, fontset=fontset)
33453345
font_output = fontset_class(prop, backend)
33463346

33473347
fontsize = prop.get_size_in_points()

lib/matplotlib/offsetbox.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,8 +1125,7 @@ def __init__(self, loc,
11251125
self.set_child(child)
11261126

11271127
if isinstance(loc, str):
1128-
cbook._check_in_list(self.codes, loc=loc)
1129-
loc = self.codes[loc]
1128+
loc = cbook._check_getitem(self.codes, loc=loc)
11301129

11311130
self.loc = loc
11321131
self.borderpad = borderpad

lib/matplotlib/testing/jpl_units/UnitDbl.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,7 @@ def __init__(self, value, units):
4747
- value The numeric value of the UnitDbl.
4848
- units The string name of the units the value is in.
4949
"""
50-
cbook._check_in_list(self.allowed, units=units)
51-
data = self.allowed[units]
50+
data = cbook._check_getitem(self.allowed, units=units)
5251
self._value = float(value * data[0])
5352
self._units = data[1]
5453

@@ -67,8 +66,7 @@ def convert(self, units):
6766
"""
6867
if self._units == units:
6968
return self._value
70-
cbook._check_in_list(self.allowed, units=units)
71-
data = self.allowed[units]
69+
data = cbook._check_getitem(self.allowed, units=units)
7270
if self._units != data[1]:
7371
raise ValueError(f"Error trying to convert to different units.\n"
7472
f" Invalid conversion requested.\n"

lib/mpl_toolkits/axisartist/axis_artist.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -452,8 +452,7 @@ def get_text(self):
452452
top=("bottom", "center"))
453453

454454
def set_default_alignment(self, d):
455-
cbook._check_in_list(["left", "right", "top", "bottom"], d=d)
456-
va, ha = self._default_alignments[d]
455+
va, ha = cbook._check_getitem(self._default_alignments, d=d)
457456
self.set_va(va)
458457
self.set_ha(ha)
459458

@@ -463,8 +462,7 @@ def set_default_alignment(self, d):
463462
top=180)
464463

465464
def set_default_angle(self, d):
466-
cbook._check_in_list(["left", "right", "top", "bottom"], d=d)
467-
self.set_rotation(self._default_angles[d])
465+
self.set_rotation(cbook._check_getitem(self._default_angles, d=d))
468466

469467
def set_axis_direction(self, d):
470468
"""
@@ -852,8 +850,8 @@ def set_ticklabel_direction(self, tick_direction):
852850
----------
853851
tick_direction : {"+", "-"}
854852
"""
855-
cbook._check_in_list(["+", "-"], tick_direction=tick_direction)
856-
self._ticklabel_add_angle = {"+": 0, "-": 180}[tick_direction]
853+
self._ticklabel_add_angle = cbook._check_getitem(
854+
{"+": 0, "-": 180}, tick_direction=tick_direction)
857855

858856
def invert_ticklabel_direction(self):
859857
self._ticklabel_add_angle = (self._ticklabel_add_angle + 180) % 360
@@ -871,8 +869,8 @@ def set_axislabel_direction(self, label_direction):
871869
----------
872870
tick_direction : {"+", "-"}
873871
"""
874-
cbook._check_in_list(["+", "-"], label_direction=label_direction)
875-
self._axislabel_add_angle = {"+": 0, "-": 180}[label_direction]
872+
self._axislabel_add_angle = cbook._check_getitem(
873+
{"+": 0, "-": 180}, label_direction=label_direction)
876874

877875
def get_transform(self):
878876
return self.axes.transAxes + self.offset_transform

lib/mpl_toolkits/mplot3d/axes3d.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -993,15 +993,12 @@ def set_proj_type(self, proj_type):
993993
994994
Parameters
995995
----------
996-
proj_type : str
997-
Type of projection, accepts 'persp' and 'ortho'.
998-
996+
proj_type : {'persp', 'ortho'}
999997
"""
1000-
cbook._check_in_list(['persp', 'ortho'], proj_type=proj_type)
1001-
if proj_type == 'persp':
1002-
self._projection = proj3d.persp_transformation
1003-
elif proj_type == 'ortho':
1004-
self._projection = proj3d.ortho_transformation
998+
self._projection = cbook._check_getitem({
999+
'persp': proj3d.persp_transformation,
1000+
'ortho': proj3d.ortho_transformation,
1001+
}, proj_type=proj_type)
10051002

10061003
def get_proj(self):
10071004
"""

0 commit comments

Comments
 (0)