Skip to content

Commit eb1c4e3

Browse files
committed
Merge pull request #9473 from shoyer/fix-is_hashable
BUG: fix common.is_hashable for NumPy scalars on Python 3
2 parents fa2b684 + 4e0b0ef commit eb1c4e3

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

pandas/core/common.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2573,13 +2573,13 @@ def is_hashable(arg):
25732573
>>> is_hashable(a)
25742574
False
25752575
"""
2576-
# don't consider anything not collections.Hashable, so as not to broaden
2577-
# the definition of hashable beyond that. For example, old-style classes
2578-
# are not collections.Hashable but they won't fail hash().
2579-
if not isinstance(arg, collections.Hashable):
2580-
return False
2576+
# unfortunately, we can't use isinstance(arg, collections.Hashable), which
2577+
# can be faster than calling hash, because numpy scalars on Python 3 fail
2578+
# this test
2579+
2580+
# reconsider this decision once this numpy bug is fixed:
2581+
# https://github.com/numpy/numpy/issues/5562
25812582

2582-
# narrow the definition of hashable if hash(arg) fails in practice
25832583
try:
25842584
hash(arg)
25852585
except TypeError:

pandas/tests/test_common.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ def __hash__(self):
424424
raise TypeError("Not hashable")
425425

426426
hashable = (
427-
1, 'a', tuple(), (1,), HashableClass(),
427+
1, 3.14, np.float64(3.14), 'a', tuple(), (1,), HashableClass(),
428428
)
429429
not_hashable = (
430430
[], UnhashableClass1(),
@@ -434,13 +434,10 @@ def __hash__(self):
434434
)
435435

436436
for i in hashable:
437-
assert isinstance(i, collections.Hashable)
438437
assert com.is_hashable(i)
439438
for i in not_hashable:
440-
assert not isinstance(i, collections.Hashable)
441439
assert not com.is_hashable(i)
442440
for i in abc_hashable_not_really_hashable:
443-
assert isinstance(i, collections.Hashable)
444441
assert not com.is_hashable(i)
445442

446443
# numpy.array is no longer collections.Hashable as of
@@ -455,7 +452,7 @@ class OldStyleClass():
455452
pass
456453
c = OldStyleClass()
457454
assert not isinstance(c, collections.Hashable)
458-
assert not com.is_hashable(c)
455+
assert com.is_hashable(c)
459456
hash(c) # this will not raise
460457

461458

0 commit comments

Comments
 (0)