10000 More robust type checking in '_validate_linestyle', on both Py2 and Py3 · matplotlib/matplotlib@0a1473e · GitHub
[go: up one dir, main page]

Skip to content

Commit 0a1473e

Browse files
committed
More robust type checking in '_validate_linestyle', on both Py2 and Py3
1 parent beeba66 commit 0a1473e

File tree

1 file changed

+29
-13
lines changed

1 file changed

+29
-13
lines changed

lib/matplotlib/rcsetup.py

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -914,24 +914,40 @@ def _validate_linestyle(ls):
914914
A validator for all possible line styles, the named ones *and*
915915
the on-off ink sequences.
916916
"""
917-
# Named line style, like u'--' or u'solid'
918-
if isinstance(ls, six.text_type):
919-
return _validate_named_linestyle(ls)
920-
921-
# On-off ink (in points) sequence *of even length*.
917+
# Look first for a valid named line style, like '--' or 'solid'
918+
if isinstance(ls, six.string_types):
919+
try:
920+
return _validate_named_linestyle(ls)
921+
except (UnicodeDecodeError, KeyError):
922+
# On Python 2, string-like *ls*, like for example
923+
# 'solid'.encode('utf-16'), may raise a unicode error.
924+
raise ValueError("the linestyle string {!r} is not a valid "
925+
"string.".format(ls))
926+
927+
if isinstance(ls, (bytes, bytearray)):
928+
# On Python 2, a string-like *ls* should already have lead to a
929+
# successful return or to raising an exception. On Python 3, we have
930+
# to manually raise an exception in the case of a byte-like *ls*.
931+
# Otherwise, if *ls* is of even-length, it will be passed to the
932+
# instance of validate_nseq_float, which will return an absurd on-off
933+
# ink sequence...
934+
raise ValueError("linestyle {!r} neither looks like an on-off ink "
935+
"sequence nor a valid string.".format(ls))
936+
937+
# Look for an on-off ink sequence (in points) *of even length*.
922938
# Offset is set to None.
923939
try:
924940
if len(ls) % 2 != 0:
925-
# Expecting a sequence of even length
926-
raise ValueError
941+
raise ValueError("the linestyle sequence {!r} is not of even "
942+
"length.".format(ls))
943+
927944
return (None, validate_nseq_float()(ls))
928-
except (ValueError, TypeError):
929-
# TypeError can be raised by wrong types passed to float()
930-
# (called inside the instance of validate_nseq_float).
931-
pass
932945

933-
raise ValueError("linestyle must be a string or " +
934-
"an even-length sequence of floats.")
946+
except (ValueError, TypeError):
947+
# TypeError can be raised inside the instance of validate_nseq_float,
948+
# by wrong types passed to float(), like NoneType.
949+
raise ValueError("linestyle {!r} is not a valid on-off ink "
950+
"sequence.".format(ls))
935951

936952

937953
# a map from key -> value, converter

0 commit comments

Comments
 (0)
0