Python 3D Academyবাংলা

__eq__ and __lt__: comparing objects

🌍 In real life. You and a friend each have a 500-taka note. They are two different pieces of paper, but at a shop they are worth the same: either one buys the same things.

Python can't guess what "the same" means for your class. Without help, a == b only asks "is this the very same object?", like asking whether two notes are one piece of paper. Watch: two Money objects with the same amount, and still a == b is False.

The idea in one sentence: __eq__ teaches == what "equal" means for your class, and __lt__ teaches <, which also makes sorted, min and max work.

Its words:

  • __eq__(self, other): return True when the two count as equal
  • __lt__(self, other): return True when self is smaller
  • identity: without __eq__, == only checks whether they're the very same object

Teach your class what equal means with __eq__(self, other). Return True when the two should count as equal. Python turns a == b into a.__eq__(b), and a != b uses it too.

To say which one is smaller, write __lt__(self, other) ("less than"). Then < works, and so do sorted(), min() and max(), because they all compare with <.

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def __lt__(self, other):
        return self.marks < other.marks

    def __repr__(self):
        return f"{self.name}({self.marks})"

students = [Student("Ana", 82), Student("Bo", 67), Student("Cy", 91)]
print(sorted(students))
print(min(students), max(students))
sorted(), min() and max() all use your __lt__ to decide who comes first.

Step by step, for any comparison method:

  1. it takes self (the left side) and other (the right side)
  2. compare the attributes that matter, like self.marks < other.marks
  3. return True or False; forgetting return gives None, which counts as False

The other four for free: @total_ordering. With only __eq__ and __lt__, < works but a > b and a <= b still need methods of their own. Put @total_ordering (from functools) above the class, and Python writes <=, > and >= from the two you gave.

from functools import total_ordering


@total_ordering
class Money:
    def __init__(self, amount):
        self.amount = amount

    def __eq__(self, other):
        return self.amount == other.amount

    def __lt__(self, other):
        return self.amount < other.amount


a, b = Money(500), Money(100)
print(a > b, a >= b, b <= a, a != b)

Why must I write them? Python can't guess which attributes matter: two Money objects might be equal by amount, two students by roll number. You decide, once, in one method, and every ==, < and sorted() uses that rule.

Mistakes and edge cases.

  • Comparing without lt. m1 < m2 gives TypeError: '<' not supported between instances of 'M' and 'M'.
  • Forgetting return. A comparison method that returns nothing gives None, which counts as False.
  • eq without hash. Writing __eq__ makes objects unhashable, so they can't go in a set (Lesson 24.5).
  • Comparing different types. money == 5 calls your __eq__ with an int; check the type first, or other.amount raises an AttributeError.

Quiz

  1. What does this print?

    class Note:
        def __init__(self, value):
            self.value = value
    
    a = Note(500)
    b = Note(500)
    print(a == b, a == a)
  2. What does this print?

    class Note:
        def __init__(self, value):
            self.value = value
    
        def __eq__(self, other):
            return self.value == other.value
    
    print(Note(500) == Note(500), Note(500) != Note(100))
  3. What does Python turn x < y into?

    • x.__lt__(y)
    • y.__lt__(x)
    • x.__eq__(y)
  4. What does this print?

    class Box:
        def __init__(self, size):
            self.size = size
    
        def __lt__(self, other):
            return self.size < other.size
    
    boxes = [Box(5), Box(2), Box(9)]
    print([b.size for b in sorted(boxes)])
  5. Which line has a mistake?

    class Card:
        def __init__(self, rank):
            self.rank = rank
    
        def __eq__(self, other):
            self.rank == other.rank
    
    print(Card(7) == Card(7))
  6. A class defines eq and lt and has @total_ordering above it. Which comparisons work?

    • All six: ==, !=, <, <=, > and >=
    • Only == and <
    • Only <, because total_ordering replaces __eq__

Coding tasks

  1. Give Note an __eq__ so two notes are equal when they have the same value.

  2. Give Student an __lt__ that compares marks, so sorted() puts students from the lowest marks to the highest.

  3. Write a class Parcel(weight) with __eq__ (same weight) and __lt__ (lighter comes first).