8000 Fold _make_nseq_validator into _listify_validator. · matplotlib/matplotlib@28c7b23 · GitHub
[go: up one dir, main page]

Skip to content

Commit 28c7b23

Browse files
committed
Fold _make_nseq_validator into _listify_validator.
It's easy to also check the length of the value in _listify_validator; no need to have a second nearly identical "list-validator". Also deprecate validate_nseq_int and validate_nseq_float as a result.
1 parent db783f7 commit 28c7b23
8000

File tree

3 files changed

+49
-35
lines changed

3 files changed

+49
-35
lines changed

doc/api/api_changes_3.3/deprecations.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,8 @@ The following validators, defined in `.rcsetup`, are deprecated:
238238
``validate_axes_titlelocation``, ``validate_toolbar``,
239239
``validate_ps_papersize``, ``validate_legend_loc``,
240240
``validate_bool_maybe_none``, ``validate_hinting``,
241-
``validate_movie_writers``, ``validate_webagg_address``.
241+
``validate_movie_writers``, ``validate_webagg_address``,
242+
``validate_nseq_float``, ``validate_nseq_int``.
242243
To test whether an rcParam value would be acceptable, one can test e.g. ``rc =
243244
RcParams(); rc[k] = v`` raises an exception.
244245

lib/matplotlib/rcsetup.py

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"""
1515

1616
import ast
17-
from functools import partial, reduce
17+
from functools import lru_cache, reduce
1818
import logging
1919
from numbers import Number
2020
import operator
@@ -81,18 +81,19 @@ def __call__(self, s):
8181
raise ValueError(msg)
8282

8383

84-
def _listify_validator(scalar_validator, allow_stringlist=False, *, doc=None):
84+
@lru_cache()
85+
def _listify_validator(scalar_validator, allow_stringlist=False, *,
86+
n=None, doc=None):
8587
def f(s):
8688
if isinstance(s, str):
8789
try:
88-
return [scalar_validator(v.strip()) for v in s.split(',')
89-
if v.strip()]
90+
val = [scalar_validator(v.strip()) for v in s.split(',')
91+
if v.strip()]
9092
except Exception:
9193
if allow_stringlist:
9294
# Sometimes, a list of colors might be a single string
9395
# of single-letter colornames. So give that a shot.
94-
return [scalar_validator(v.strip())
95-
for v in s if v.strip()]
96+
val = [scalar_validator(v.strip()) for v in s if v.strip()]
9697
else:
9798
raise
9899
# Allow any ordered sequence type -- generators, np.ndarray, pd.Series
@@ -102,11 +103,16 @@ def f(s):
102103
# behavior of filtering out any empty strings (behavior was
103104
# from the original validate_stringlist()), while allowing
104105
# any non-string/text scalar values such as numbers and arrays.
105-
return [scalar_validator(v) for v in s
106-
if not isinstance(v, str) or v]
106+
val = [scalar_validator(v) for v in s
107+
if not isinstance(v, str) or v]
107108
else:
108-
raise ValueError("{!r} must be of type: str or non-dictionary "
109-
"iterable".format(s))
109+
raise ValueError(
110+
f"Expected str or other non-set iterable, but got {s}")
111+
if n is not None and len(val) != n:
112+
raise ValueError(
113+
f"Expected {n} values, but there are {len(val)} values in {s}")
114+
return val
115+
110116
try:
111117
f.__name__ = "{}list".format(scalar_validator.__name__)
112118
except AttributeError: # class instance.
@@ -295,6 +301,7 @@ def validate_backend(s):
295301
_deprecated_since="3.3")
296302

297303

304+
@cbook.deprecated("3.3")
298305
def _make_nseq_validator(cls, n=None, allow_none=False):
299306

300307
def validator(s):
@@ -320,8 +327,14 @@ def validator(s):
320327
return validator
321328

322329

323-
validate_nseq_float = partial(_make_nseq_validator, float)
324-
validate_nseq_int = partial(_make_nseq_validator, int)
330+
@cbook.deprecated("3.3")
331+
def validate_nseq_float(n):
332+
return _make_nseq_validator(float, n)
333+
334+
335+
@cbook.deprecated("3.3")
336+
def validate_nseq_int(n):
337+
return _make_nseq_validator(int, n)
325338

326339

327340
def validate_color_or_inherit(s):
@@ -480,12 +493,10 @@ def validate_whiskers(s):
480493
return 'range'
481494
else:
482495
try:
483-
v = validate_nseq_float(2)(s)
484-
return v
496+
return _listify_validator(validate_float, n=2)(s)
485497
except (TypeError, ValueError):
486498
try:
487-
v = float(s)
488-
return v
499+
return float(s)
489500
except ValueError as e:
490501
raise ValueError("Not a valid whisker value ['range', float, "
491502
"(float, float)]") from e
@@ -746,7 +757,7 @@ def validate_sketch(s):
746757
if s == 'none' or s is None:
747758
return None
748759
try:
749-
return tuple(validate_nseq_float(3)(s))
760+
return tuple(_listify_validator(validate_float, n=3)(s))
750761
except ValueError:
751762
raise ValueError("Expected a (scale, length, randomness) triplet")
752763

@@ -1226,7 +1237,7 @@ def _convert_validator_spec(key, conv):
12261237
"axes.labelcolor": validate_color, # color of axis label
12271238
# use scientific notation if log10 of the axis range is smaller than the
12281239
# first or larger than the second
1229-
"axes.formatter.limits": validate_nseq_int(2),
1240+
"axes.formatter.limits": _listify_validator(validate_int, n=2),
12301241
# use current locale to format ticks
12311242
"axes.formatter.use_locale": validate_bool,
12321243
"axes.formatter.use_mathtext": validate_bool,
@@ -1351,7 +1362,7 @@ def _convert_validator_spec(key, conv):
13511362
"figure.titleweight": validate_fontweight,
13521363

13531364
# figure size in inches: width by height
1354-
"figure.figsize": validate_nseq_float(2),
1365+
"figure.figsize": _listify_validator(validate_float, n=2),
13551366
"figure.dpi": validate_float,
13561367
"figure.facecolor": validate_color,
13571368
"figure.edgecolor": validate_color,

lib/matplotlib/tests/test_rcparams.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,21 @@
1414
import matplotlib.pyplot as plt
1515
import matplotlib.colors as mcolors
1616
import numpy as np
17-
from matplotlib.rcsetup import (validate_bool_maybe_none,
18-
validate_stringlist,
19-
validate_colorlist,
20-
validate_color,
21-
validate_bool,
22-
validate_fontweight,
23-
validate_nseq_int,
24-
validate_nseq_float,
25-
validate_cycler,
26-
validate_hatch,
27-
validate_hist_bins,
28-
validate_markevery,
29-
_validate_linestyle)
17+
from matplotlib.rcsetup import (
18+
validate_bool,
19+
validate_bool_maybe_none,
20+
validate_color,
21+
validate_colorlist,
22+
validate_cycler,
23+
validate_float,
24+
validate_fontweight,
25+
validate_hatch,
26+
validate_hist_bins,
27+
validate_int,
28+
validate_markevery,
29+
validate_stringlist,
30+
_validate_linestyle,
31+
_listify_validator)
3032

3133

3234
def test_rcparams(tmpdir):
@@ -229,7 +231,7 @@ def generate_validator_testcases(valid):
229231
(1, ValueError),
230232
)
231233
},
232-
{'validator': validate_nseq_int(2),
234+
{'validator': _listify_validator(validate_int, n=2),
233235
'success': ((_, [1, 2])
234236
for _ in ('1, 2', [1.5, 2.5], [1, 2],
235237
(1, 2), np.array((1, 2)))),
@@ -238,7 +240,7 @@ def generate_validator_testcases(valid):
238240
(1, 2, 3)
239241
))
240242
},
241-
{'validator': validate_nseq_float(2),
243+
{'validator': _listify_validator(validate_float, n=2),
242244
'success': ((_, [1.5, 2.5])
243245
for _ in ('1.5, 2.5', [1.5, 2.5], [1.5, 2.5],
244246
(1.5, 2.5), np.array((1.5, 2.5)))),

0 commit comments

Comments
 (0)
0