
Equal & Hashable
By default, == between two objects asks "are these the same object?"
To compare by value, define __eq__:
def __eq__(self, other):
if not isinstance(other, Coord):
return NotImplemented # "I don't know how to compare these"
return (self.x, self.y) == (other.x, other.y)
Sets and dict keys use hashes to find things fast. The golden rule:
objects that are equal must have equal hashes. So when you define
__eq__, Python sets __hash__ to None. Your objects become
unhashable. Add the hash back by hashing the same fields as a tuple:
def __hash__(self):
return hash((self.x, self.y))
Only do this for objects you won't change after creating them; a hash
that changes while the object sits in a set breaks the set.
(A frozen=True dataclass does all of this for you!)
The bug
The map-maker wants a set of visited coordinates. But the program
crashes with a TypeError ending in unhashable type: 'Coord'. Even the equality
check is wrong: Coord(1, 2) == Coord(1, 9) says True.
Assignment
- Fix
__eq__so it compares bothxandy. - Add a matching
__hash__. The program should print2.
- Fix
__eq__so it compares bothxandy. - Add a matching
__hash__. The program should print2.
Press Run to try your code, then Check to test it.