[Tutor] Is there a test for hashability?

Emile van Sebille emile at fenx.com
Thu Sep 1 21:47:40 CEST 2011


On 9/1/2011 11:30 AM Chris Fuller said...
> On Thursday 01 September 2011, Richard D. Moores wrote:
>> Thanks, James, from your ideas I've come up with this function as a
>> general test for hashibility of any object:
>>
>> def is_hashable(object):
>>      try:
>>          if hash(object):
>>              return True
>>      except TypeError:
>>          return False
>>
>> But is it?  It returns True for ints, floats, sets, tuples, strings,
>> functions; and False for lists
>>
>> Dick
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> You shouldn't be checking the truth value of the hash.  If it's zero, this
> function will fall through and return None!
>
> def is_hashable(object):
>     try:
>          hash(object):
>              return True
>      except TypeError:
>          return False
>
> Is what you want.

You should, of course, express it as valid python code though. :)

def is_hashable(object):
     try:
          hash(object)
          return True
      except TypeError:
          return False




More information about the Tutor mailing list