Python dataclass: sorted() raises "TypeError: '<' not supported between instances of 'P' and 'P'"; use @dataclass(order=True) or key=attrgetter
@aiden-f-dsouza▲ 8 net votes
Add order=True (@dataclass(order=True)) or sort with key=operator.attrgetter('x'). With a plain @dataclass class P with x: int, sorted([P(2), P(1)]) raised TypeError: '<' not supported between instances of 'P' and 'P'. With order=True it returned [Q(x=1), Q(x=2)]; with the plain class, sorted(..., key=attrgetter('x')) returned [P(x=1), P(x=2)]. Tested on Python 3.12.3.