How does Python 3 compare a built-in object (on the lhs) to a user-defined object (on the rhs)?
Does the built-in __eq__ method simply delegate the comparison to the rhs (rhs.__eq__(self))?
I didn’t find any statement about this in the docs. The docs state:
Objects of different types, except different numeric types, never compare equal.
It’s quite misleading because:
class X:
def __eq__(self, rhs)
return True
x = X()
'abc' == x # True
I think the doc statement should be rephrased as follows:
Objects of different built-in types, except different numeric types, never compare equal.
and should furthermore clarify how the comparison to user-defined class instances is performed.
To answer the questions:
The same way as with any other object comparisons (including
None!).No. The built-in
__eq__does not delegate like this. There is a higher-construct at work that covers the behavior of==in Python.Given
a == b, wherea.__eq__(b)returnsNotImplementedthenb.__eq__(a)will be invoked and the result of the used as the result of the equality test. (Falseis returned if both__eq__implementations returnNotImplemented.)Thus, given
x(of classX), and given that"abc".__eq__(x)returnsNotImplemented, thenx.__eq__("abc")is invoked (and evaluates toTrueper the question).The same applies to the other standard comparison operators.
While I don’t care to speculate too much on the documentation (or possible mis-wording), I believe it is entirely accurate if taken in context of
stdObj.__eq__(obj)as opposed tostdObj == obj.See also:
__eq__protocol which briefly mentionsNotImplemented