Lesson 3 of 10

When are two objects equal?

Goal

Dict keys and set members

01

Explanation

Unless you define equality yourself, == between two objects asks "are these the same object?" rather than "do they hold the same values?". That's why Point(1, 2) == Point(1, 2) gives False, and your set of visited points fills up with duplicates.

__eq__ defines equality by value. If the other side is a type you don't know, return NotImplemented, not False, so Python can give the other object its turn to compare before deciding.

The classic trap is that defining __eq__ on its own removes __hash__. The object can no longer go in a set or serve as a dict key, and you get TypeError: unhashable type. The rule is that equal objects must have the same hash, so compute it from the same fields you compare. And don't change those fields once the object is in a set, or it gets lost inside the set.

02

Your task

Give Point an __eq__ method that compares x and y and returns NotImplemented when the other side isn't a point, plus a __hash__ method that agrees with it.

Checks

6 checks
  1. Two points with the same coordinates are equal
  2. Different points are not equal
  3. Comparing with another type gives False without an error
  4. Equal points share a hash
  5. A point works as a dict key
  6. A set drops duplicate points
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.