Sub topic 8
Equality and ordering with eq and order
This chapter assumes you know how @dataclass generates methods, how to declare fields with defaults, and what __eq__ and __lt__ do on a plain class. Here you will see how the decorator compares instances and how to turn on sorting.
What eq=True generates
@dataclass takes eq=True by default. It generates an __eq__ method that compares the fields as tuples, in the order you declared them.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
a = Point(1, 2)
b = Point(1, 2)
print(a == b) # True
print(a is b) # False
print(a == (1, 2)) # FalseTwo separate instances with equal fields are equal. The last line is False because the generated method only compares instances of the same class. For any other type it returns NotImplemented, so Python falls back to identity and the result is False. A Point never equals a plain tuple, and a subclass instance never equals its parent class instance.
Turning on ordering with order=True
By default, dataclasses define no ordering, so Card(1, "H") < Card(2, "H") raises TypeError. Pass order=True to generate __lt__, __le__, __gt__ and __ge__.
from dataclasses import dataclass
@dataclass(order=True)
class Card:
rank: int
suit: str
hand = [Card(10, "H"), Card(2, "S"), Card(10, "C")]
print(sorted(hand))
# [Card(rank=2, suit='S'), Card(rank=10, suit='C'), Card(rank=10, suit='H')]
print(Card(2, "S") < Card(10, "C")) # TrueThe comparison is lexicographic, like tuple comparison. Python compares rank first and only looks at suit when the ranks tie. So field order in the class body is the sort order. If you declare suit before rank, the cards sort by suit first.
Ordering uses the same same-class rule as equality. Comparing a Card to a tuple raises TypeError.
try:
Card(1, "H") < (1, "H")
except TypeError as e:
print("TypeError:", e)Excluding fields with compare=False
Often some fields should not take part in comparison, such as a description or a cache. Use field(compare=False). Excluded fields are ignored by == and by ordering.
from dataclasses import dataclass, field
@dataclass(order=True)
class Task:
priority: int
title: str = field(compare=False)
t1 = Task(1, "write report")
t2 = Task(1, "answer email")
print(t1 == t2) # True
print(min(Task(3, "c"), Task(2, "b")).title) # bt1 == t2 is True because only priority counts. This is useful for priority queues and sorting, but it can surprise you: two tasks with different titles are "equal".
Rules and errors
| Setting | Result |
|---|---|
| `eq=True` (default) | `__eq__` is generated |
| `eq=False` | `__eq__` is inherited, which usually means identity comparison |
| `order=True` with `eq=True` | Ordering methods are generated |
| `order=True` with `eq=False` | `ValueError` when the class is created |
| `order=True` and the class defines `__lt__` yourself | `TypeError` when the class is created |
The decorator refuses to overwrite ordering methods you wrote, because a silent replacement would hide your logic. If you need custom ordering, define the methods yourself and leave order off.
Common mistakes
- Expecting
Point(1, 2) == (1, 2)to beTrue. Useastuple(p)when you need a tuple comparison. - Reordering fields during a refactor and silently changing the sort order.
- Using
compare=Falseon a field and then being surprised that unequal-looking objects compare equal. - Comparing floats exactly. A generated
__eq__uses==on each field, so0.1 + 0.2and0.3are different.
Exercise
Given @dataclass(order=True) class Job: name: str; priority: int, which job does min([Job("b", 1), Job("a", 5)]) return, and how would you make it sort by priority instead?
Show answer
It returns Job(name='a', priority=5), because name is compared first and "a" < "b". To sort by priority, declare priority before name, or mark name with field(compare=False) if the name should not affect comparison at all.
Exercise
What happens when you define @dataclass(eq=False, order=True) class A: x: int?
Show answer
Python raises ValueError when the class is defined, because ordering requires eq=True.