Operator commutativity

Westley Martínez anikom15 at gmail.com
Mon Sep 19 22:53:39 EDT 2011


On Mon, Sep 19, 2011 at 10:26:30PM -0400, Roy Smith wrote:
> 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.

Calling __radd__ = __add__ simply creates a reference to __add__ named
__radd__, it doesn't create a new method.



More information about the Python-list mailing list