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

Skip to content

Commit 6d3610b

Browse files
authored
Merge pull request #7996 from anntzer/is_numlike_stringlike
Simplify implementation of is_numlike & is_string_like.
2 parents 6de05b6 + 6b716cf commit 6d3610b

File tree

3 files changed

+12
-22
lines changed

3 files changed

+12
-22
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
`cbook.is_numlike` and `cbook.is_string_like` only perform an instance check
2+
````````````````````````````````````````````````````````````````````````````
3+
4+
`cbook.is_numlike` and `cbook.is_string_like` now only check that
5+
their argument is an instance of ``(numbers.Number, np.Number)`` and
6+
``(six.string_types, np.str_, np.unicode_)`` respectively. In particular, this
7+
means that arrays are now never num-like or string-like regardless of their
8+
dtype.

lib/matplotlib/cbook/__init__.py

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import gzip
2121
import io
2222
import locale
23+
import numbers
2324
import os
2425
import re
2526
import sys
@@ -495,19 +496,8 @@ def iterable(obj):
495496

496497
def is_string_like(obj):
497498
"""Return True if *obj* looks like a string"""
498-
if isinstance(obj, six.string_types):
499-
return True
500-
# numpy strings are subclass of str, ma strings are not
501-
if isinstance(obj, np.ma.MaskedArray):
502-
if obj.ndim == 0 and obj.dtype.kind in 'SU':
503-
return True
504-
else:
505-
return False
506-
try:
507-
obj + ''
508-
except:
509-
return False
510-
return True
499+
# (np.str_ == np.unicode_ on Py3).
500+
return isinstance(obj, (six.string_types, np.str_, np.unicode_))
511501

512502

513503
def is_sequence_of_strings(obj):
@@ -560,12 +550,7 @@ def is_scalar(obj):
560550

561551
def is_numlike(obj):
562552
"""return true if *obj* looks like a number"""
563-
try:
564-
obj + 1
565-
except:
566-
return False
567-
else:
568-
return True
553+
return isinstance(obj, (numbers.Number, np.number))
569554

570555

571556
def to_filehandle(fname, flag='rU', return_opened=False):

lib/matplotlib/tests/test_cbook.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,6 @@ def test_is_string_like():
3434
y = np.array(y)
3535
assert not cbook.is_string_like(y)
3636

37-
y = np.array(y, dtype=object)
38-
assert cbook.is_string_like(y)
39-
4037

4138
def test_is_sequence_of_strings():
4239
y = ['a', 'b', 'c']

0 commit comments

Comments
 (0)