How to determine if something is hashable?

Remco Gerlich scarblac at pino.selwerd.nl
Mon Jun 25 18:27:27 EDT 2001


Andrew Post <apost at cbmi.upmc.edu> wrote in comp.lang.python:
> Hello,
> 
> I want to write a function that takes a list of keys and a list of 
> values and returns a hash. I want to test, however, that all of the 
> items in the list of keys are hashable. How do I do this? The only way 
> that I've come up with so far is to do:
> 
> try:
>      myDict[ keyList[ i ] ] = valList[ i ]
> except (TypeError):
>      print keyList[ i ], 'is not hashable'
> 
> TypeError isn't specific to finding a non-hashable key, though, right?

In that case, I don't see what else could raise TypeError though.

But you can try more explicitly with:

try:
   hash(valList[i])
except TypeError:
   ...

-- 
Remco Gerlich



More information about the Python-list mailing list