diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index 730ced7299865e..5a7c7678e5f2dd 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -1180,21 +1180,27 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, if order: # Create and set the ordering methods. flds = [f for f in field_list if f.compare] - self_tuple = _tuple_str('self', flds) - other_tuple = _tuple_str('other', flds) + match flds: + # Special-case single field comparisons. See GH-144191. + case [single_fld]: + self_expr = f'self.{single_fld.name}' + other_expr = f'other.{single_fld.name}' + case _: + self_expr = _tuple_str('self', flds) + other_expr = _tuple_str('other', flds) for name, op in [('__lt__', '<'), ('__le__', '<='), ('__gt__', '>'), ('__ge__', '>='), ]: # Create a comparison function. If the fields in the object are - # named 'x' and 'y', then self_tuple is the string - # '(self.x,self.y)' and other_tuple is the string + # named 'x' and 'y', then self_expr is the string + # '(self.x,self.y)' and other_expr is the string # '(other.x,other.y)'. func_builder.add_fn(name, ('self', 'other'), [ ' if other.__class__ is self.__class__:', - f' return {self_tuple}{op}{other_tuple}', + f' return {self_expr}{op}{other_expr}', ' return NotImplemented'], overwrite_error='Consider using functools.total_ordering') diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py index 3b335429b98500..cd4435c5b647a9 100644 --- a/Lib/test/test_dataclasses/__init__.py +++ b/Lib/test/test_dataclasses/__init__.py @@ -406,6 +406,16 @@ class C: self.assertGreaterEqual(C(1), C(0)) self.assertGreaterEqual(C(1), C(1)) + @dataclass(order=True) + class C2: + x: int + y: int = field(compare=False) + + self.assertLess(C2(0, 10), C2(1, -5)) + self.assertLessEqual(C2(1, 10), C2(1, -5)) + self.assertGreater(C2(2, -1), C2(1, 999)) + self.assertGreaterEqual(C2(1, 10), C2(1, -5)) + def test_simple_compare(self): # Ensure that order=False is the default. @dataclass diff --git a/Misc/NEWS.d/next/Library/2026-01-26-14-51-22.gh-issue-144191.jHXZrc.rst b/Misc/NEWS.d/next/Library/2026-01-26-14-51-22.gh-issue-144191.jHXZrc.rst new file mode 100644 index 00000000000000..17224ec35d5ad9 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-01-26-14-51-22.gh-issue-144191.jHXZrc.rst @@ -0,0 +1 @@ +Dataclass ordering methods were adjusted to simplify comparisons for classes with a single comparison field, aligning the generated behaviour more closely with hand-written comparison logic.