mirror of https://github.com/python/cpython
Small speedup for dataclass __eq__ and __repr__ (#104904)
Faster __repr__ with str.__add__ moved inside the f-string. For __eq__ comp;are field by field instead of building temporary tuples. Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
This commit is contained in:
parent
c8c1e73d95
commit
18cfc1eea5
|
@ -627,7 +627,7 @@ def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
|
||||||
def _repr_fn(fields, globals):
|
def _repr_fn(fields, globals):
|
||||||
fn = _create_fn('__repr__',
|
fn = _create_fn('__repr__',
|
||||||
('self',),
|
('self',),
|
||||||
['return self.__class__.__qualname__ + f"(' +
|
['return f"{self.__class__.__qualname__}(' +
|
||||||
', '.join([f"{f.name}={{self.{f.name}!r}}"
|
', '.join([f"{f.name}={{self.{f.name}!r}}"
|
||||||
for f in fields]) +
|
for f in fields]) +
|
||||||
')"'],
|
')"'],
|
||||||
|
@ -1085,13 +1085,17 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
|
||||||
if eq:
|
if eq:
|
||||||
# Create __eq__ method. There's no need for a __ne__ method,
|
# Create __eq__ method. There's no need for a __ne__ method,
|
||||||
# since python will call __eq__ and negate it.
|
# since python will call __eq__ and negate it.
|
||||||
flds = [f for f in field_list if f.compare]
|
cmp_fields = (field for field in field_list if field.compare)
|
||||||
self_tuple = _tuple_str('self', flds)
|
terms = [f'self.{field.name}==other.{field.name}' for field in cmp_fields]
|
||||||
other_tuple = _tuple_str('other', flds)
|
field_comparisons = ' and '.join(terms) or 'True'
|
||||||
_set_new_attribute(cls, '__eq__',
|
body = [f'if other.__class__ is self.__class__:',
|
||||||
_cmp_fn('__eq__', '==',
|
f' return {field_comparisons}',
|
||||||
self_tuple, other_tuple,
|
f'return NotImplemented']
|
||||||
globals=globals))
|
func = _create_fn('__eq__',
|
||||||
|
('self', 'other'),
|
||||||
|
body,
|
||||||
|
globals=globals)
|
||||||
|
_set_new_attribute(cls, '__eq__', func)
|
||||||
|
|
||||||
if order:
|
if order:
|
||||||
# Create and set the ordering methods.
|
# Create and set the ordering methods.
|
||||||
|
|
Loading…
Reference in New Issue