Skip to content

Commit 94ef589

Browse files
committed
speedup compare methods
1 parent 3000594 commit 94ef589

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

Lib/dataclasses.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,18 @@ def _tuple_str(obj_name, fields):
433433
return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
434434

435435

436+
def _tuple_compare_expand(op, fields):
437+
if fields:
438+
for f in fields[:-1]:
439+
yield (
440+
f' if self.{f.name} != other.{f.name}:\n'
441+
f' return self.{f.name} {op} other.{f.name}'
442+
)
443+
yield f' return self.{fields[-1].name} {op} other.{fields[-1].name}'
444+
else:
445+
yield ' return True'
446+
447+
436448
class _FuncBuilder:
437449
def __init__(self, globals):
438450
self.names = []
@@ -1128,21 +1140,20 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
11281140
if order:
11291141
# Create and set the ordering methods.
11301142
flds = [f for f in field_list if f.compare]
1131-
self_tuple = _tuple_str('self', flds)
1132-
other_tuple = _tuple_str('other', flds)
11331143
for name, op in [('__lt__', '<'),
11341144
('__le__', '<='),
11351145
('__gt__', '>'),
11361146
('__ge__', '>='),
11371147
]:
11381148
# Create a comparison function. If the fields in the object are
1139-
# named 'x' and 'y', then self_tuple is the string
1140-
# '(self.x,self.y)' and other_tuple is the string
1141-
# '(other.x,other.y)'.
1149+
# named 'x' and 'y'.
1150+
# if self.x != other.x:
1151+
# return self.x {op} other.x
1152+
# return self.y {op} other.y
11421153
func_builder.add_fn(name,
11431154
('self', 'other'),
11441155
[ ' if other.__class__ is self.__class__:',
1145-
f' return {self_tuple}{op}{other_tuple}',
1156+
*_tuple_compare_expand(op, flds),
11461157
' return NotImplemented'],
11471158
overwrite_error='Consider using functools.total_ordering')
11481159

0 commit comments

Comments
 (0)