Operator commutativity

Terry Reedy tjreedy at udel.edu
Mon Sep 19 11:25:04 EDT 2011


On 9/19/2011 8:48 AM, Ethan Furman wrote:
> Roy Smith wrote:

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

The builtin classes like int are (should be, sans bug) well-behaved.

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

So the potential problems arise with two user classes.

-- 
Terry Jan Reedy




More information about the Python-list mailing list