diff --git a/doc/api/api_changes/2017-01-30-AL_is_numlike_stringlike.rst b/doc/api/api_changes/2017-01-30-AL_is_numlike_stringlike.rst new file mode 100644 index 000000000000..ba062de5d71a --- /dev/null +++ b/doc/api/api_changes/2017-01-30-AL_is_numlike_stringlike.rst @@ -0,0 +1,8 @@ +`cbook.is_numlike` and `cbook.is_string_like` only perform an instance check +```````````````````````````````````````````````````````````````````````````` + +`cbook.is_numlike` and `cbook.is_string_like` now only check that +their argument is an instance of ``(numbers.Number, np.Number)`` and +``(six.string_types, np.str_, np.unicode_)`` respectively. In particular, this +means that arrays are now never num-like or string-like regardless of their +dtype. diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 74a5082c7065..48fd0bd93eb2 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -20,6 +20,7 @@ import gzip import io import locale +import numbers import os import re import sys @@ -495,19 +496,8 @@ def iterable(obj): def is_string_like(obj): """Return True if *obj* looks like a string""" - if isinstance(obj, six.string_types): - return True - # numpy strings are subclass of str, ma strings are not - if isinstance(obj, np.ma.MaskedArray): - if obj.ndim == 0 and obj.dtype.kind in 'SU': - return True - else: - return False - try: - obj + '' - except: - return False - return True + # (np.str_ == np.unicode_ on Py3). + return isinstance(obj, (six.string_types, np.str_, np.unicode_)) def is_sequence_of_strings(obj): @@ -560,12 +550,7 @@ def is_scalar(obj): def is_numlike(obj): """return true if *obj* looks like a number""" - try: - obj + 1 - except: - return False - else: - return True + return isinstance(obj, (numbers.Number, np.number)) def to_filehandle(fname, flag='rU', return_opened=False): diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index d0aff6e3e6ab..73c81ff1a230 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -34,9 +34,6 @@ def test_is_string_like(): y = np.array(y) assert not cbook.is_string_like(y) - y = np.array(y, dtype=object) - assert cbook.is_string_like(y) - def test_is_sequence_of_strings(): y = ['a', 'b', 'c']