I thought returning NotImplemented from __add__ will pass to __radd__ under all circumstances, but apparently this is not true if it’s the same class?
class A:
def __add__(self, other):
print("add")
return NotImplemented
def __radd__(self, other):
print("radd")
return 100
A()+A()
# TypeError: unsupported operand type(s) for +: 'A' and 'A'
Am I missing something?
>Solution :
The reflected methods (like __radd__) are only used
if the left operand does not support the corresponding operation and the operands are of different types.
Since the type of A() is the same as the type of A(), the +-operation fails without consulting __radd__.
See also the footnote on exactly this point
For operands of the same type, it is assumed that if the non-reflected method – such as
__add__()– fails then the overall operation is not supported, which is why the reflected method is not called.