3

When implementing the __eq__ function I was wondering if testing for identity using the is keyword should be part of the test? Testing for equality for 2 different variables can immediately evaluate to True by the is function when variables point to the same object instance. In case variables point to different instances further testing is needed of course. Say we have S = U then obviously we want S == U to return True and testing for identity will speed this up.

def __eq__(self, other):
    if self is other:
        return True
    else:
        pass # do another user defined test for equality 
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
Elmex80s
  • 3,428
  • 1
  • 15
  • 23
  • 2
    I'd say not generally, unless your `__eq__` is expensive for some reason. If, for example, you will just check if some members are equal, even if they are "complex" (like strings or lists) Python's internal implementation will surely do the check. An example where I would probably do it is for a tree data structure. – jdehesa Mar 22 '18 at 13:03

1 Answers1

1

You could implement this, although it will likely be a bit of a micro-optimisation for most uses cases. This optimisation idea was applied by the Python core developers for how they implemented the in operator for lists; the code is C (in CPython) but the equivalent Python logic would be:

any(element is target or element == target for element in lst)

However, be aware this may not be exactly what you want, for example, numpy.NAN is numpy.NAN is True but numpy.NAN == numpy.NAN is False. This is however an unusual case.

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119