|
| 1 | +import collections |
1 | 2 | from datetime import datetime
|
2 | 3 | import re
|
| 4 | +import sys |
3 | 5 |
|
4 | 6 | import nose
|
5 | 7 | from nose.tools import assert_equal
|
@@ -398,6 +400,55 @@ def test_is_list_like():
|
398 | 400 | assert not com.is_list_like(f)
|
399 | 401 |
|
400 | 402 |
|
| 403 | +def test_is_hashable(): |
| 404 | + |
| 405 | + # all new-style classes are hashable by default |
| 406 | + class HashableClass(object): |
| 407 | + pass |
| 408 | + |
| 409 | + class UnhashableClass1(object): |
| 410 | + __hash__ = None |
| 411 | + |
| 412 | + class UnhashableClass2(object): |
| 413 | + def __hash__(self): |
| 414 | + raise TypeError("Not hashable") |
| 415 | + |
| 416 | + hashable = ( |
| 417 | + 1, 'a', tuple(), (1,), HashableClass(), |
| 418 | + ) |
| 419 | + not_hashable = ( |
| 420 | + [], UnhashableClass1(), |
| 421 | + ) |
| 422 | + abc_hashable_not_really_hashable = ( |
| 423 | + ([],), UnhashableClass2(), |
| 424 | + ) |
| 425 | + |
| 426 | + for i in hashable: |
| 427 | + assert isinstance(i, collections.Hashable) |
| 428 | + assert com.is_hashable(i) |
| 429 | + for i in not_hashable: |
| 430 | + assert not isinstance(i, collections.Hashable) |
| 431 | + assert not com.is_hashable(i) |
| 432 | + for i in abc_hashable_not_really_hashable: |
| 433 | + assert isinstance(i, collections.Hashable) |
| 434 | + assert not com.is_hashable(i) |
| 435 | + |
| 436 | + # numpy.array is no longer collections.Hashable as of |
| 437 | + # https://github.com/numpy/numpy/pull/5326, just test |
| 438 | + # pandas.common.is_hashable() |
| 439 | + assert not com.is_hashable(np.array([])) |
| 440 | + |
| 441 | + # old-style classes in Python 2 don't appear hashable to |
| 442 | + # collections.Hashable but also seem to support hash() by default |
| 443 | + if sys.version_info[0] == 2: |
| 444 | + class OldStyleClass(): |
| 445 | + pass |
| 446 | + c = OldStyleClass() |
| 447 | + assert not isinstance(c, collections.Hashable) |
| 448 | + assert not com.is_hashable(c) |
| 449 | + hash(c) # this will not raise |
| 450 | + |
| 451 | + |
401 | 452 | def test_ensure_int32():
|
402 | 453 | values = np.arange(10, dtype=np.int32)
|
403 | 454 | result = com._ensure_int32(values)
|
|
0 commit comments