When implementing a custom equality function for a class, does it make sense to check for identity first? An example:
def __eq__(self, other):
return (self is other) or (other criteria)
This interesting is for cases when the other criteria may be more expensive (e.g. comparing some long strings).
Summary. Implement the Python __eq__ method to define the equality logic for comparing two objects using the equal operator ( == )
The == operator helps us compare the equality of objects. The is operator helps us check whether different variables point towards a similar object in the memory. We use the == operator in Python when the values of both the operands are very much equal.
== is for value equality. It's used to know if two objects have the same value. is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical.
Comparing Equality With the Python == and != Use the equality operators == and != if you want to check whether or not two objects have the same value, regardless of where they're stored in memory.
It may be a perfectly reasonable shortcut to check for identity first, and in equality methods good shortcuts (for both equality and non equality) are what you should be looking for so that you can return as soon as possible.
But, on the other hand, it could also be a completely superfluous check if your test for equality is otherwise cheap and you are unlikely in practice to be comparing an object with itself.
For example, if equality between objects can be gauged by comparing one or two integers then this should be quicker than the identity test, so in less than the time it would take to compare id
s you've got the whole answer. And remember that if you check the identities and the objects don't have the same id
(which is likely in most scenarios) then you've not gained anything as you've still got to do the full check.
So if full equality checking is not cheap and it's possible that an object could be compared against itself, then checking identity first can be a good idea.
Note that another reason the check isn't done by default is that it is quite reasonable (though rare) for objects with equal identities to compare as non equal, for example:
>>> s = float('nan')
>>> s == s
False
necesarry: no
does it make sense: sure, why not?
No such check is done by default, as you can see here:
class bad(object):
def __eq__(self, other):
return False
x = bad()
print x is x, x==x # True, False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With