Operator commutativity

Ethan Furman ethan at stoneleaf.us
Mon Sep 19 14:48:07 CEST 2011


Roy Smith wrote:
> In article <j5797e$s57$1 at speranza.aioe.org>,
>  Henrik Faber <hfaber at invalid.net> wrote:
> 
>> On 19.09.2011 13:23, Paul Rudin wrote:
>>> Henrik Faber <hfaber at invalid.net> writes:
>>>
>>>> How can I make this commutative?
>>> Incidentally - this isn't really about commutativity at all - the
>>> question is how can you define both left and right versions of add,
>>> irrespective of whether they yield the same result.
>> Right. The operator+ in my case just happens to be commutative and I
>> wanted a language way to express this.
>>
>>> I think __radd__ is what you're after.
>> It is, thank you very much - I knew there was some way to get this done
>> nicely. Perfect! :-)
> 
> __radd__() only solves the problem if the left-hand operand has no 
> __add__() method itself.

Only true if the left-hand operand is so ill-behaved it doesn't check to 
see if it makes sense to add itself to the right-hand operand.  If it 
doesn't know how, it should `return NotImplemented` -- Python will then 
try __radd__ on the left-hand operand.

Also, if the right-hand operand is a subclass of the left-hand operand 
then Python will try right-hand_operand.__radd__ first.

Now, if the left-hand operand *does* know how (or thinks it does, which 
could be another matter entirely), and the right-hand operand is *not* a 
subclass of the left-hand operand, then you are correct -- the 
right-hand operand wil not be called.

~Ethan~



More information about the Python-list mailing list