Sub topic 8
Equality and Ordering with eq and order
This chapter covers how @dataclass decides whether two instances are equal and how it lets you sort them. It assumes you know how == calls __eq__, how < calls __lt__, and how sorted() uses them. It also assumes you have read the chapters on fields and field() options.
What eq=True generates
eq is a parameter of @dataclass and defaults to True. With it on, the decorator writes an __eq__ method for you. That method compares the instances' fields as if they were two tuples, in the order the fields were declared.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
@dataclass
class Vector:
x: int
y: int
print(Point(1, 2) == Point(1, 2)) # True
print(Point(1, 2) is Point(1, 2)) # False
print(Point(1, 2) == Vector(1, 2)) # False
print(Point(1, 2) == (1, 2)) # FalseTwo separate Point objects are not the same object, so is returns False. They are equal in value, so == returns True. Equality is also strict about type. A Point never equals a Vector with the same numbers, and it never equals a plain tuple.
The generated method works roughly like this:
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.x, self.y) == (other.x, other.y)
return NotImplementedReturning NotImplemented is the standard signal that this method cannot answer. Python then tries the reflected method on the other operand. If that also returns NotImplemented, Python falls back to comparing identity, so == gives False.
Subclasses are not equal to their parents
The class check is exact (is), not isinstance. An instance of a subclass never equals an instance of its parent, even when every field matches.
from dataclasses import dataclass
@dataclass
class Base:
x: int
@dataclass
class Child(Base):
pass
print(Base(1) == Child(1)) # False
print(Child(1) == Child(1)) # TrueThis keeps == symmetric, so a == b and b == a always agree. It can surprise you if you expect isinstance-style behavior.
Leaving fields out with compare=False
Some fields are bookkeeping and should not affect equality. Set compare=False on those fields, and they are skipped in __eq__. They are skipped in the ordering methods too, which are covered below.
from dataclasses import dataclass, field
@dataclass
class Document:
doc_id: int
title: str
last_opened: float = field(default=0.0, compare=False)
a = Document(1, "Plan", 100.0)
b = Document(1, "Plan", 250.0)
print(a == b) # True
print(a) # Document(doc_id=1, title='Plan', last_opened=100.0)compare=False leaves the field in __init__ and __repr__. Only the comparison methods ignore it.
Turning on ordering with order=True
The order parameter defaults to False. When you set it to True, the decorator generates __lt__, __le__, __gt__ and __ge__. Each one compares the field tuples, so the first field has the highest priority. If two instances tie on the first field, the second field decides, and so on.
from dataclasses import dataclass
@dataclass(order=True)
class Student:
grade: int
name: str
students = [Student(90, "Ben"), Student(85, "Zoe"), Student(90, "Ana")]
print(sorted(students))
# [Student(grade=85, name='Zoe'), Student(grade=90, name='Ana'), Student(grade=90, name='Ben')]
print(max(students)) # Student(grade=90, name='Ben')
print(Student(1, "a") < Student(1, "b")) # True
try:
Student(1, "a") < (1, "a")
except TypeError as e:
print(e) # '<' not supported between instances of 'Student' and 'tuple'Ordering follows the same class rule as equality. Comparing with another type returns NotImplemented, which Python turns into a TypeError. Because sorted, min and max only need <, they work directly on the instances.
Field order is therefore part of your design. If you want to sort by grade first and name second, declare grade before name. Reordering the declarations changes the sort order, and it also changes the positional arguments of __init__.
Summary of the eq and order combinations
| `eq` | `order` | Result |
|---|---|---|
| `True` (default) | `False` (default) | Generates `__eq__`. Sets `__hash__` to `None` unless `frozen=True`. |
| `True` | `True` | Also generates `__lt__`, `__le__`, `__gt__`, `__ge__`. |
| `False` | `False` | Generates nothing. Equality and hashing stay identity-based, inherited from `object`. |
| `False` | `True` | Raises `ValueError` when the class is defined. |
Errors you will meet
Ordering depends on equality, so asking for order=True while turning eq off is rejected at class-definition time.
from dataclasses import dataclass
try:
@dataclass(eq=False, order=True)
class Bad:
x: int
except ValueError as e:
print(e) # eq must be true if order is trueThe decorator also refuses to overwrite ordering methods you wrote yourself. If your class body defines any of __lt__, __le__, __gt__ or __ge__ and you pass order=True, you get a TypeError.
from dataclasses import dataclass
try:
@dataclass(order=True)
class Custom:
x: int
def __lt__(self, other):
return self.x < other.x
except TypeError as e:
print(e)
# Cannot overwrite attribute __lt__ in class Custom. Consider using functools.total_orderingEquality behaves differently. If you define __eq__ in the class body, eq=True leaves your method alone and raises no error. The decorator only fills in what is missing.
You can see the effect directly:
from dataclasses import dataclass
@dataclass
class Item:
sku: int
@dataclass(eq=False)
class Handle:
sku: int
try:
hash(Item(1))
except TypeError as e:
print(e) # unhashable type: 'Item'
print(Handle(1) == Handle(1)) # False: identity comparison again
print(len({Handle(1), Handle(1)})) # 2Use eq=False when instances stand for distinct things, such as connections or handles, and two of them should never count as the same object.
Controlling the sort order
Sometimes the order you want does not match the order of the fields. Three approaches cover most cases.
- Reorder the fields. This is the simplest option, but it also changes the constructor signature.
- Pass a key to
sorted. The class stays unchanged, and each call site chooses its own order. This is the right choice when different parts of your program sort the same objects differently. - Add a hidden sort field. The class defines one fixed natural order, computed in
__post_init__.
Here is the third approach. The sort_index field is excluded from __init__ and __repr__. The other fields are excluded from comparison, so only sort_index takes part.
from dataclasses import dataclass, field
@dataclass(order=True)
class Task:
sort_index: int = field(init=False, repr=False)
name: str = field(compare=False)
priority: int = field(compare=False)
def __post_init__(self):
self.sort_index = -self.priority # higher priority sorts first
tasks = [Task("write", 2), Task("test", 5), Task("ship", 1)]
print([t.name for t in sorted(tasks)]) # ['test', 'write', 'ship']
print(Task("test", 5)) # Task(name='test', priority=5)The hidden field is computed once, when the object is created. If priority changes later, sort_index goes stale. For mutable objects, a key= function passed to sorted is safer. Another option is to make the class frozen=True, so the value cannot change.
Gotchas
- Field order is comparison order. Adding a field in the middle of a class silently changes how existing instances sort.
- Every compared field needs its own ordering. If a field holds values that do not support
<, such asNonemixed with integers, sorting raisesTypeErrorwhen Python reaches that field. This only happens when all earlier fields tie. - Floats compare exactly.
Point(0.1 + 0.2, 0) == Point(0.3, 0)isFalse. If you need tolerance, write a custom method and keep the default==strict. - Mixed types never compare. Comparing a dataclass to a tuple or dict with
==always givesFalse. Convert one side first withastupleorasdict, which a later chapter covers. - Comparison uses the live field values. Equality on a mutable dataclass reflects its state at the moment of the call. Mutating an object after sorting a list does not re-sort it.
Exercise
Given the class below, what do a == b and a < b evaluate to? Explain which fields take part in each comparison.
from dataclasses import dataclass, field
@dataclass(order=True)
class Entry:
key: str
value: int
note: str = field(default="", compare=False)
a = Entry("k", 5, "first")
b = Entry("k", 7, "second")
Show answer
a == b is False and a < b is True. Only key and value are compared, because note has compare=False. The keys tie, so value decides, and 5 is less than 7. If the values were equal, the different notes would not matter and a == b would be True.
Exercise
A teammate writes @dataclass(eq=False, order=True) on a class. What happens, and why does Python behave that way?
Show answer
A ValueError is raised when the class is defined, with the message "eq must be true if order is true". The ordering methods are built on the same field comparison as __eq__. Turning equality off while asking for ordering would leave the class inconsistent, so the decorator rejects it.
Exercise
You have @dataclass class Job: name: str; priority: int. You want to sort jobs by priority, highest first, in one function only. Which approach fits, and what is the one-line code?
Show answer
Use the key approach, because only one call site needs this order and the class does not need to change. The code is sorted(jobs, key=lambda j: j.priority, reverse=True). A hidden sort_index field or order=True is not needed.