Python 3.7+dataclassesfunction
@dataclass(order=True)
basics
order=True adds the __lt__, __le__, __gt__ and __ge__ methods, comparing the fields as a tuple.
Syntax
@dataclass(order=True)
class X:
a: int; b: int
Comparison walks all fields in declaration order, as if they were a tuple — you cannot pick a key on the fly, so the field order in the class effectively defines the sort order; exclude unwanted fields with field(compare=False). Combining order=True with eq=False is forbidden and raises ValueError. Comparing against a different class returns NotImplemented, which surfaces as a TypeError rather than a quiet False.
Examples
from dataclasses import dataclass
@dataclass(order=True)
class Version:
major: int
minor: int
v1 = Version(1, 0)
v2 = Version(2, 0)
v1 < v2 # → True
sorted([Version(2,0), Version(1,5)]) # → [Version(1,5), Version(2,0)]
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy