◐ Shell
clean mode source ↗

Small speedup for dataclass __eq__ and __repr__ by rhettinger · Pull Request #104904 · python/cpython

  1. Have__eq__ do a series of and comparisons rather than building a tuple and relying on tuple.__eq__.
  2. Let __repr__ put the type name in the f-string rather than calling string concatenation explicitly.

Old code:

 def __eq__(self,other):
  if other.__class__ is self.__class__:
   return (self.a,self.b,)==(other.a,other.b,)

 def __repr__(self):
  return self.__class__.__qualname__ + f"(a={self.a!r}, b={self.b!r})"

New code:

 def __eq__(self,other):
  if other.__class__ is self.__class__:
   return self.a==other.a and self.b==other.b

 def __repr__(self):
  return f"{self.__class__.__qualname__}(a={self.a!r}, b={self.b!r})"

Timings for a dataclass with two integer fields:

             Both Equal     First Equal    Neither Equal        Repr
             ==========     ===========    =============    ============
Baseline     0.09769874     0.10188975     0.10144600       0.18586733
With PR      0.08537712     0.08647508     0.070007080      0.18308112