hash-equals contract
The rule that if two objects are equal, a == b, then their hashes must be equal too, hash(a) == hash(b).
In more detail
A hash table first uses the hash to find a slot and then uses equality to confirm the key, so equal objects with different hashes would never be found. The rule only runs one way: unequal objects may share a hash, which is just a collision. In Python, define __hash__ from the same fields that __eq__ compares, and only use immutable fields.
Related terms
- hashable — Describes a Python object that has a hash value that never changes during its lifetime and can be compared for equality, so it can be a dict key or set member.
- special method — A Python method with a double-underscore name, such as __eq__ or __hash__, that the language calls automatically for built-in operations.
- collision — Two different keys producing the same hash, or the same slot in a hash table.
Taught in
- Python Dicts And Sets Under The Hood — Algorithms & Data Structures for Working Engineers