Inspect hashability
Checking whether a value exposes hashing behavior before using it as a dictionary key.
Python · Function
hash() returns an integer hash value for an object that provides one. Python uses hashes to speed dictionary-key lookup, and equal numeric values share the same hash even across types.
hash() returns an integer hash value for an object when that object provides one. Python uses these values to compare dictionary keys efficiently; custom hash implementations are constrained by the host machine's integer width.
hash(object, /)| Name | Type | Description |
|---|---|---|
object | object | The object whose hash value should be returned; it must provide a hash value. |
An integer hash value, if the object has one.
key = ("user", 42)
print(hash(key))Computes the integer hash for a tuple, which is suitable for use as a dictionary key.
Checking whether a value exposes hashing behavior before using it as a dictionary key.
Implementing or reviewing custom classes that define __hash__().
Understanding dictionary behavior for numerically equal keys such as 1 and 1.0.
hash() returns an integer for an object that has a hash value. Dictionary lookup uses hash values to compare keys quickly.
Follow-up: What equality rule should numeric keys follow? Values that compare equal must produce the same hash, even when their types differ.
Objects without a hash value cannot be passed successfully to hash(). Hashable values can participate in dictionary-key lookup.
Follow-up: Why might a mutable object be unsuitable as a key? Mutating key-relevant state can invalidate the hash-based lookup assumptions.
Equal numeric values share a hash, so 1 and 1.0 produce the same hash even though they have different types. This preserves consistent dictionary-key behavior.
Follow-up: What implementation detail affects custom hash results? Python truncates custom __hash__() results to the host machine's bit width.
__hash__()dictdictionary keys