Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Loading