Пример #1
0
def test_is_hashable():

    # all new-style classes are hashable by default
    class HashableClass(object):
        pass

    class UnhashableClass1(object):
        __hash__ = None

    class UnhashableClass2(object):
        def __hash__(self):
            raise TypeError("Not hashable")

    hashable = (
        1,
        'a',
        tuple(),
        (1, ),
        HashableClass(),
    )
    not_hashable = (
        [],
        UnhashableClass1(),
    )
    abc_hashable_not_really_hashable = (
        ([], ),
        UnhashableClass2(),
    )

    for i in hashable:
        assert isinstance(i, collections.Hashable)
        assert com.is_hashable(i)
    for i in not_hashable:
        assert not isinstance(i, collections.Hashable)
        assert not com.is_hashable(i)
    for i in abc_hashable_not_really_hashable:
        assert isinstance(i, collections.Hashable)
        assert not com.is_hashable(i)

    # numpy.array is no longer collections.Hashable as of
    # https://github.com/numpy/numpy/pull/5326, just test
    # pandas.common.is_hashable()
    assert not com.is_hashable(np.array([]))

    # old-style classes in Python 2 don't appear hashable to
    # collections.Hashable but also seem to support hash() by default
    if sys.version_info[0] == 2:

        class OldStyleClass():
            pass

        c = OldStyleClass()
        assert not isinstance(c, collections.Hashable)
        assert not com.is_hashable(c)
        hash(c)  # this will not raise
Пример #2
0
def test_is_hashable():

    # all new-style classes are hashable by default
    class HashableClass(object):
        pass

    class UnhashableClass1(object):
        __hash__ = None

    class UnhashableClass2(object):

        def __hash__(self):
            raise TypeError("Not hashable")

    hashable = (1,
                3.14,
                np.float64(3.14),
                'a',
                tuple(),
                (1, ),
                HashableClass(), )
    not_hashable = ([], UnhashableClass1(), )
    abc_hashable_not_really_hashable = (([], ), UnhashableClass2(), )

    for i in hashable:
        assert com.is_hashable(i)
    for i in not_hashable:
        assert not com.is_hashable(i)
    for i in abc_hashable_not_really_hashable:
        assert not com.is_hashable(i)

    # numpy.array is no longer collections.Hashable as of
    # https://github.com/numpy/numpy/pull/5326, just test
    # pandas.common.is_hashable()
    assert not com.is_hashable(np.array([]))

    # old-style classes in Python 2 don't appear hashable to
    # collections.Hashable but also seem to support hash() by default
    if compat.PY2:

        class OldStyleClass():
            pass

        c = OldStyleClass()
        assert not isinstance(c, collections.Hashable)
        assert com.is_hashable(c)
        hash(c)  # this will not raise