Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit b2159ef

Browse filesBrowse files
authored
Merge pull request #14662 from anntzer/check_getitem
MNT: Add a _check_getitem helper to go with _check_in_list/_check_isinstance.
2 parents 73d7119 + 08bff55 commit b2159ef
Copy full SHA for b2159ef

File tree

Expand file treeCollapse file tree

9 files changed

+60
-49
lines changed
Filter options
Expand file treeCollapse file tree

9 files changed

+60
-49
lines changed

‎lib/matplotlib/axes/_axes.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axes/_axes.py
+2-4Lines 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

Copy file name to clipboardExpand all lines: lib/matplotlib/axis.py
+6-12Lines 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

Copy file name to clipboardExpand all lines: lib/matplotlib/backends/backend_cairo.py
+2-4Lines 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

Copy file name to clipboardExpand all lines: lib/matplotlib/cbook/__init__.py
+34-5Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2054,17 +2054,23 @@ def _check_and_log_subprocess(command, logger, **kwargs):
20542054
return proc.stdout
20552055

20562056

2057-
def _check_isinstance(types, **kwargs):
2057+
# In the following _check_foo functions, the first parameter starts with an
2058+
# underscore because it is intended to be positional-only (e.g., so that
2059+
# `_check_isinstance([...], types=foo)` doesn't fail.
2060+
2061+
2062+
def _check_isinstance(_types, **kwargs):
20582063
"""
20592064
For each *key, value* pair in *kwargs*, check that *value* is an instance
2060-
of one of *types*; if not, raise an appropriate TypeError.
2065+
of one of *_types*; if not, raise an appropriate TypeError.
20612066
2062-
As a special case, a ``None`` entry in *types* is treated as NoneType.
2067+
As a special case, a ``None`` entry in *_types* is treated as NoneType.
20632068
20642069
Examples
20652070
--------
20662071
>>> cbook._check_isinstance((SomeClass, None), arg=arg)
20672072
"""
2073+
types = _types
20682074
if isinstance(types, type) or types is None:
20692075
types = (types,)
20702076
none_allowed = None in types
@@ -2088,17 +2094,40 @@ def type_name(tp):
20882094
type_name(type(v))))
20892095

20902096

2091-
def _check_in_list(values, **kwargs):
2097+
def _check_in_list(_values, **kwargs):
20922098
"""
2093-
For each *key, value* pair in *kwargs*, check that *value* is in *values*;
2099+
For each *key, value* pair in *kwargs*, check that *value* is in *_values*;
20942100
if not, raise an appropriate ValueError.
20952101
20962102
Examples
20972103
--------
20982104
>>> cbook._check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg)
20992105
"""
2106+
values = _values
21002107
for k, v in kwargs.items():
21012108
if v not in values:
21022109
raise ValueError(
21032110
"{!r} is not a valid value for {}; supported values are {}"
21042111
.format(v, k, ', '.join(map(repr, values))))
2112+
2113+
2114+
def _check_getitem(_mapping, **kwargs):
2115+
"""
2116+
*kwargs* must consist of a single *key, value* pair. If *key* is in
2117+
*_mapping*, return ``_mapping[value]``; else, raise an appropriate
2118+
ValueError.
2119+
2120+
Examples
2121+
--------
2122+
>>> cbook._check_getitem({"foo": "bar"}, arg=arg)
2123+
"""
2124+
mapping = _mapping
2125+
if len(kwargs) != 1:
2126+
raise ValueError("_check_getitem takes a single keyword argument")
2127+
(k, v), = kwargs.items()
2128+
try:
2129+
return mapping[v]
2130+
except KeyError:
2131+
raise ValueError(
2132+
"{!r} is not a valid value for {}; supported values are {}"
2133+
.format(v, k, ', '.join(map(repr, mapping)))) from None

‎lib/matplotlib/mathtext.py

Copy file name to clipboardExpand all lines: lib/matplotlib/mathtext.py
+2-2Lines 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

Copy file name to clipboardExpand all lines: lib/matplotlib/offsetbox.py
+1-2Lines 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

Copy file name to clipboardExpand all lines: lib/matplotlib/testing/jpl_units/UnitDbl.py
+2-4Lines 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

Copy file name to clipboardExpand all lines: lib/mpl_toolkits/axisartist/axis_artist.py
+6-8Lines 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

Copy file name to clipboardExpand all lines: lib/mpl_toolkits/mplot3d/axes3d.py
+5-8Lines 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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.