1

Keys of dictionaries must be hashable. Therefore list and dict are inappropriate.

However tuple is hashable, but fails as a key if any of its elements is not.

Is there another way than catching the exception to check if a container is suitable as a key?

def is_hashable(obj):
    try:
        hash(obj)            # this will throw an exception if 'obj' is not hashable
        return True
    except TypeError as err:
        return False

t1 = ("a", "b", "c")
is_hashable(t1)              # True

t2 = ("a", {"b":2}, {"c":3})
is_hashable(t2)              # False
AFoeee
  • 731
  • 7
  • 24
  • I like your method. – 101 Nov 05 '18 at 06:31
  • @101: While it would work, obviously, using it in a function like this just adds overhead to something that's built-in. Besides, type-checking using a function like this (or the built-in one) is unpythonic. The recommended way to do it is to catch exceptions via `try/except` anywhere you need to deal with them—not buried in a function to essentially hide them (and needs to always be called it first). – martineau Nov 05 '18 at 07:25

0 Answers0