Lesson · Python Data Model & Special Methods
Object Identity, Equality & Hashing
55 min readObject Identity, Equality & Hashing
Identity asks whether two names refer to the same object, while equality asks whether values compare equal. Hashing adds the invariant required by dictionaries and sets: equal hashable objects must have equal hashes.
Learning goals
- Explain what
istests, and why two equalUserinstances still fail it. - Write an
__eq__that returnsNotImplementedfor foreign types so Python can try the reflected comparison. - Explain why defining
__eq__without__hash__makes instances unhashable, and whathash(self.user_id)restores. - State the hash invariant and point out where the worked example's set literal depends on it.
- Diagnose what goes wrong when a hashed attribute changes after the object sits in a dict or set.
Mental model
The three questions are independent. In the worked example a and b are equal but not identical: a == b is true through __eq__, while a is b is false because they are two distinct User(1) objects. The set {a, b} needs both methods to agree, because a dict or set picks a bucket with hash and confirms the candidate with __eq__.
Mental model
read it top to bottom
is same object? identity, ignores __eq__ == same value? calls __eq__, falls back to identity hash same bucket? equal objects must hash equal
Core idea
The data model separates three questions that look similar in code: which object a name points at (is), which values count as the same (== through __eq__), and where a hash table starts looking (hash through __hash__). The contract that binds them is simple and strict: any two objects that compare equal must produce the same hash, because dict and set lookups pick a bucket by hash and then let __eq__ confirm the candidate found there.
is
is compares object identity: a is b is true only when both names refer to the same object, never merely because the values compare equal. It asks whether id(a) == id(b), ignoring __eq__ entirely, so User(1) is User(1) is false while a is a is true. Use it for singletons such as None and sentinel objects, not for value comparisons.
==
== asks whether two values compare equal: Python calls __eq__ on the left operand, and when that returns NotImplemented it tries the reflected operation on the right operand. If both sides decline, the result falls back to identity, so two objects without a custom __eq__ are equal only when they are the same object. The worked example's a == b prints True because User.__eq__ compares user_id.
__eq__
__eq__ defines value equality. Returning NotImplemented for unsupported comparisons gives Python a chance to try the reflected operation or conclude that the values are unequal.
__hash__
__hash__ produces the integer used by hash tables. If equality depends on mutable state, instances usually must not remain hashable.
Hash invariants
The hash invariant says that if a == b then hash(a) == hash(b); the reverse does not hold, and collisions between unequal objects are legal but cost extra equality checks. A second rule belongs to containers: a key's hash must not change while it sits in a dict or set, which is why hashed attributes should not be mutable. The worked example satisfies both by hashing the stable user_id, the same field __eq__ compares.
Hashable objects
An object is hashable when hash() returns an integer that never changes during its lifetime and __eq__ stays consistent with it. Immutable built-ins such as int, str, and tuples of hashables qualify; list, dict, and set do not, because their contents can change. Dict keys and set members must be hashable, which is exactly why User.__hash__ has to exist before {a, b} will build.
Dictionary/set key behavior
A dict or set stores keys in a hash table: it computes hash(key), jumps to the matching bucket, then uses == to confirm the candidate found there. Two keys that compare equal must therefore produce the same hash, or the lookup can land in the wrong bucket and report the key missing. The worked example relies on this: {a, b} keeps a single element because hash(a) == hash(b) and a == b are both true.
Walkthrough
User.__init__storesuser_id;__eq__first checksisinstance(other, User)and returnsNotImplementedfor anything else, which lets Python try the other operand's reflected comparison before giving up.- The comparison itself is
self.user_id == other.user_id, soa == bprintsTrueeven thougha is bisFalse: two separate objects built from the same id are equal by value. __hash__returnshash(self.user_id). Without it, defining__eq__sets the class's__hash__toNone, andlen({a, b})would raiseTypeErrorbecause unhashable instances cannot enter a set; with it, both objects land in the same bucket and the set keeps just one.- Predict before running: the exact line
True False 1, and what the set length becomes if__hash__is deleted or ifuser_iddiffers.
Experiments to try
- Delete
__hash__and rerun the set line: read theTypeErrorand explain why Python marks the class unhashable as soon as__eq__is defined. - Return
Falseinstead ofNotImplementedfrom__eq__fora == 1, then swap back. Explain which choice lets another class supply its own reflected comparison. - Change
__hash__toreturn hash(id(self))so it disagrees with__eq__: watchlen({a, b})become2anda in {b}becomeFalse, then explain the invariant that broke. - Insert
ainto a dict as a key, mutatea.user_id, and fetch it back. Explain why the entry is still stored but no longer reachable.
Common mistakes
- Defining
__eq__and forgetting__hash__: Python sets the class's__hash__toNone, so every set insert or dict key raisesTypeErroruntil one is defined. - Letting
__hash__and__eq__use different fields: equal objects land in different buckets and lookups miss even though the entries are present. - Replacing a value comparison with
is: identity is only guaranteed for singletons such asNone, so two equalUserinstances fail anischeck. - Mutating an attribute after the object becomes a key, which invalidates the hash it was stored under and strands the entry.
Practice: Easy
- Run the worked example and record the printed triple. Then add
print(a is a, a is User(1))and explain both results with identity versus equality. - Add an
emailfield toUserand fold it into__eq__and__hash__; check thatUser(1, "ada@x") == User(1, "ada@x")is true and that a set of the two collapses to one element. - Delete
__eq__fromUserand compareUser(1) == User(1)with the original result; name the default behavior that produces the new answer.
Practice: Medium
- Build a
Point(x, y)class with value equality and a matching hash, storePoint(1, 2)as a dict key, and fetch it back with a freshPoint(1, 2)to confirm the lookup succeeds. - Make
Point.__eq__returnNotImplementedwhenotheris not aPoint, show thatPoint(1, 2) == "point"ends upFalsewithout raising, and compare that with returningFalsedirectly. - Compare
xandyin__eq__but hash onlyx, then run a set holdingPoint(1, 2)andPoint(1, 3). Explain the collisions you see, and why hashing extra fields instead breaks correctness.
Practice: Hard
- Design an immutable
Idvalue type usable as a dict key: one attribute,__eq__comparing it,__hash__mirroring it, and no mutators. Write assertions for equal hashes, set collapse, and a successful dict round trip. - Build a failure lab with three reproductions:
__eq__without__hash__and theTypeErrorfrom a set; a hashed attribute mutated after insertion that strands the key; and alistattribute passed tohash(). Explain each mechanism and its fix. - Trace the worked example through dict internals:
hash(a), bucket selection, then thea == bconfirmation. Describe what happens when two unequal keys collide in the same bucket, and how that differs from two equal keys.
Lesson checklist
- I can explain what
iscompares and why two equalUserobjects fail it. - I can write
__eq__that returnsNotImplementedfor foreign types, and__hash__that agrees with it. - I can state the hash invariant and show where the set
{a, b}depends on it. - I can explain why mutating an object after it is used as a key breaks lookups.
Remember
Identity, equality, and hashing answer three different questions about a value, and the worked example ties them together: `__eq__` compares `user_id`, `__hash__` mirrors it, and the set literal collapses two distinct objects into one element. The pitfall to carry forward is mutable hash state: keep `__hash__` aligned with `__eq__`, and do not change hashed attributes while the object lives in a dict or set.
Interview angles
What is the main purpose of **is**?+
is compares object identity, so a is b is true only when both names refer to the same object; it never calls __eq__. That is why a is a is true while two equal User(1) instances fail the check; reserve it for singletons such as None.
What should you pay attention to when using **==**?+
== delegates to __eq__: Python tries the left operand first, then the reflected operation when that returns NotImplemented, and falls back to identity when both sides decline. Without a custom __eq__, User(1) == User(1) would be false; the worked example makes it true by comparing user_id.
How does **__eq__** fit into this lesson?+
__eq__ defines value equality. Returning NotImplemented for unsupported comparisons gives Python a chance to try the reflected operation or conclude that the values are unequal.
What happens when you define `__eq__` but not `__hash__`?+
Python sets the class's __hash__ to None, so instances become unhashable: inserting one into a set or using it as a dict key raises TypeError. Defining __hash__ (in the worked example, hash(self.user_id)) keeps instances usable as keys.