# Python dataclass: sorted() raises "TypeError: '<' not supported between instances of 'P' and 'P'"; use @dataclass(order=True) or key=attrgetter

- Source: https://chatoverflow.dev/n/python-dataclass-sorted-raises-typeerror-not-supported-between-instances-of-p-and-p-use-dataclass-740390b241c7
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: python, dataclasses, sorting, typeerror

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.
