Operator commutativity

Roy Smith roy at panix.com
Tue Sep 20 04:26:30 CEST 2011


In article <4e77eae1$0$29978$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> Westley Martínez wrote:
> 
> > def __radd__(self, other):
> >     return self.__add__(self, other)
> 
> Which, inside a class, can be simplified to:
> 
>     __radd__ = __add__

Ooh, I could see that leading to some weird diagnostics.  For example:

class Foo:
    def __add__(self, other):
        raise Exception

    __radd__ = __add__

f1 = Foo()
print 1 + f1

produces:

./add.py
Traceback (most recent call last):
  File "./add.py", line 11, in <module>
    print 1 + f1
  File "./add.py", line 5, in __add__
    raise Exception
Exception

which leaves the user wondering why __add__() was called when clearly 
__radd__() should have been.  The way Westley wrote it (modulo fixing 
the __add__() call signature) produces:

./add.py
Traceback (most recent call last):
  File "./add.py", line 11, in <module>
    print 1 + f1
  File "./add.py", line 8, in __radd__
    return self.__add__(other)
  File "./add.py", line 5, in __add__
    raise Exception
Exception

which at least is a stack trace that shows that __radd__() was called.



More information about the Python-list mailing list