Operator commutativity

Ethan Furman ethan at stoneleaf.us
Wed Sep 21 21:11:12 CEST 2011


Steven D'Aprano wrote:
> After playing around with various combinations of C1, C2, D1 and D2, it
> seems to me that the rule is:
> 
> If the right-hand argument is a subclass of the left-hand argument, AND also
> defines __radd__ directly rather than inheriting it, then its __radd__
> method is called before the left-hand argument's __add__ method.
> 
> 
> which strikes me as a strangely specific and not very useful rule. I suspect
> it might be an accident of implementation rather than a deliberate feature.

Update to rule:

If the right-hand argument is a subclass of the left-hand argument AND a 
__radd__ is defined anywhere between the left-hand argument's class up 
to and including the right-hand argument's class, then __radd__ is 
called, otherwise the left-hand arguments __add__ is called.

And it makes perfect sense -- a + b is, after all, an __add__ function; 
the only reason to call __radd__ instead is if it has been defined for a 
subclass, and the only reason to define it is because it needs something 
different from a + b that a doesn't know about.

Probably not a clear explanation -- maybe somebody else can dress it up 
a bit.

~Ethan~



More information about the Python-list mailing list