With @dataclasses with the order=True , a class has its dunder comparator functions (__lt__, __gt__, etc) generated. The comparators generate code such that the class is compared as if it were a tuple. This means it's a deep comparison of every field.
For example, given:
@dataclass(order=True)
class Widget:
id: int
x: int
y: int
# the generated __eq__ dunder is similar to this
def ExampleEq(widget_a, widget_b):
if widget_a.id < widget_b.id:
return -1
elif widget_a.id > widget_b.id:
return 1
if widget_a.x < widget_b.x:
return -1
elif widget_a.x > widget_b.x:
return 1
if widget_a.y < widget_b.y:
return -1
elif widget_a.y > widget_b.y:
return 1
return 0
# pseudocode usage
w = Widget(id=0, x=1, y=1)
ExampleEq(w, w)
Ideally, if 2 Widgets have the same id, I don't want to superfluously check the x and y fields.
Is there a way to customize the generated dunder methods with dataclass so the comparison is only done on a single field? Can that field be specified and not simply be the first field in the class? Is there an alternative option to the builtin dataclass?