Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is __radd__ not called for the same class in Python?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading