What's the result of returning NotImplemented
from __eq__
special method in python 3 (well 3.5 if it matters)?
The documentation isn't clear; the only relevant text I found only vaguely refers to "some other fallback":
When
NotImplemented
is returned, the interpreter will then try the reflected operation on the other type, or some other fallback, depending on the operator. If all attempted operations returnNotImplemented
, the interpreter will raise an appropriate exception. See Implementing the arithmetic operations for more details.
Unfortunately, the "more details" link doesn't mention __eq__
at all.
My reading of this excerpt suggests that the code below should raise an "appropriate exception", but it does not:
class A:
def __eq__(self, other):
return NotImplemented
class B:
def __eq__(self, other):
return NotImplemented
# docs seems to say these lines should raise "an appropriate exception"
# but no exception is raised
a = A()
b = B()
a == b # evaluates as unequal
a == a # evaluates as equal
From experimenting, I think that when NotImplemented
is returned from __eq__
, the interpreter behaves as if __eq__
wasn't defined in the first place (specifically, it first swaps the arguments, and if that doesn't resolve the issue, it compares using the default __eq__
that evaluates "equal" if the two objects have the same identity). If that's the case, where in the documentation can I find the confirmation of this behavior?
Edit: see Python issue 28785