Re: Any built-in ishashable method ?

Discussion in 'Python' started by Peter Otten, Jan 18, 2013.

  1. Peter Otten

    Peter Otten Guest

    Jean-Michel Pichavant wrote:

    > Hello people,
    >
    > Is there any built-in way to know if an object is a valid dictionary key ?
    > From what I know, the object must be hashable, and from the python doc, an
    > object is hashable if it has the __hash__ and (__cmp__ or __eq__) methods.
    >
    > http://docs.python.org/2/glossary.html#term-hashable
    >
    > I found this on the net, but considering the above definition, does it
    > really check the cmp/eq existence ?
    >
    > def ishashable(x):
    > try:
    > hash(x)
    > except TypeError:
    > return False
    > else:
    > return True
    >
    > I was trying to know if any custom class can be used as a dict key. It
    > looks like you can. Yet I'm a little bit concerned, because last time I
    > used invalid objects as keys, I got a bug that was really difficult to
    > spot.


    Hm, but trying to put an unhashable key into a dict gives the obvious
    exception:

    >>> class A(object):

    .... __hash__ = None
    ....
    >>> {A(): 42}

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'A'

    So I'm guessing you had a key where

    key1 == key2 did not imply hash(key1) == hash(key2)

    I don't see a way to avoid that problem in a look-before-you-leap test.
    Peter Otten, Jan 18, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dave Angel

    Re: Any built-in ishashable method ?

    Dave Angel, Jan 18, 2013, in forum: Python
    Replies:
    0
    Views:
    113
    Dave Angel
    Jan 18, 2013
  2. Terry Reedy

    Re: Any built-in ishashable method ?

    Terry Reedy, Jan 18, 2013, in forum: Python
    Replies:
    0
    Views:
    118
    Terry Reedy
    Jan 18, 2013
  3. Peter Otten

    Re: Any built-in ishashable method ?

    Peter Otten, Jan 18, 2013, in forum: Python
    Replies:
    0
    Views:
    117
    Peter Otten
    Jan 18, 2013
  4. Steven D'Aprano

    Re: Any built-in ishashable method ?

    Steven D'Aprano, Jan 18, 2013, in forum: Python
    Replies:
    0
    Views:
    121
    Steven D'Aprano
    Jan 18, 2013
  5. Terry Reedy

    Re: Any built-in ishashable method ?

    Terry Reedy, Jan 18, 2013, in forum: Python
    Replies:
    0
    Views:
    121
    Terry Reedy
    Jan 18, 2013
Loading...

Share This Page