Skip to content

Commit b229292

Browse files
committed
Enhance ordering methods in dataclasses for single field cases
1 parent a126893 commit b229292

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

Lib/dataclasses.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1180,21 +1180,25 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
11801180
if order:
11811181
# Create and set the ordering methods.
11821182
flds = [f for f in field_list if f.compare]
1183-
self_tuple = _tuple_str('self', flds)
1184-
other_tuple = _tuple_str('other', flds)
1183+
if len(flds) == 1:
1184+
self_expr = f"self.{flds[0].name}"
1185+
other_expr = f"other.{flds[0].name}"
1186+
else:
1187+
self_expr = _tuple_str('self', flds)
1188+
other_expr = _tuple_str('other', flds)
11851189
for name, op in [('__lt__', '<'),
11861190
('__le__', '<='),
11871191
('__gt__', '>'),
11881192
('__ge__', '>='),
11891193
]:
11901194
# Create a comparison function. If the fields in the object are
1191-
# named 'x' and 'y', then self_tuple is the string
1192-
# '(self.x,self.y)' and other_tuple is the string
1195+
# named 'x' and 'y', then self_expr is the string
1196+
# '(self.x,self.y)' and other_expr is the string
11931197
# '(other.x,other.y)'.
11941198
func_builder.add_fn(name,
11951199
('self', 'other'),
11961200
[ ' if other.__class__ is self.__class__:',
1197-
f' return {self_tuple}{op}{other_tuple}',
1201+
f' return {self_expr}{op}{other_expr}',
11981202
' return NotImplemented'],
11991203
overwrite_error='Consider using functools.total_ordering')
12001204

0 commit comments

Comments
 (0)