Sobes.tech
Junior
304

How to determine if an object is hashable?

Answer from AI

sobes.tech AI

An object is hashable if it has a __hash__() and __eq__() method (where equal objects have the same hash), or if it is an immutable built-in object (like a string, number, or tuple), for which this behavior is guaranteed. You can check this using the hash() function. If it executes successfully, the object is hashable. If not, it will raise a TypeError.

# Example of a hashable object (string)
string_obj = "hello"
try:
    hash_value_string = hash(string_obj)
    print(f"Object '{string_obj}' is hashable. Hash: {hash_value_string}")
except TypeError as e:
    print(f"Object '{string_obj}' is not hashable: {e}")

# Example of a non-hashable object (list)
list_obj = [1, 2, 3]
try:
    hash_value_list = hash(list_obj)
    print(f"Object '{list_obj}' is hashable. Hash: {hash_value_list}")
except TypeError as e:
    print(f"Object '{list_obj}' is not hashable: {e}")

# Example of a custom class with __hash__ and __eq__ implemented
class MyHashable:
    def __init__(self, value):
        self.value = value

    def __hash__(self):
        return hash(self.value) # Delegates hashing to the internal value

    def __eq__(self, other):
        if isinstance(other, MyHashable):
            return self.value == other.value
        return False

hashable_instance = MyHashable("example")
try:
    hash_value_custom = hash(hashable_instance)
    print(f"Custom object is hashable. Hash: {hash_value_custom}")
except TypeError as e:
    print(f"Custom object is not hashable: {e}")

You can also use isinstance with collections.abc.Hashable (though this does not guarantee correct __eq__ implementation):

import collections

# Check if objects are hashable
print(f"Is a string hashable? {isinstance('abc', collections.abc.Hashable)}")
print(f"Is a list hashable? {isinstance([1, 2], collections.abc.Hashable)}")
print(f"Is a custom object hashable? {isinstance(hashable_instance, collections.abc.Hashable)}")

Hashable objects are necessary for use as keys in dictionaries (dict) and elements in sets (set).