This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: reflected operator not used when operands have the same type
Type: Stage:
Components: Interpreter Core Versions: Python 2.4
process
Status: closed Resolution: duplicate
Dependencies: Superseder:
Assigned To: Nosy List: hughsw
Priority: normal Keywords:

Created on 2005-02-28 01:23 by hughsw, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg24405 - (view) Author: Hugh Secker-Walker (hughsw) Date: 2005-02-28 01:23
The reflected operators, e.g. __radd__, are used when
the left operand does not have the non-reflected
operator, *unless* the right operand is of the same type.

The documentation on the "Emulating numeric types" page
doesn't mention this peculiar exclusion.  Of the
reflected operators it says:
"These methods are called to implement the binary
arithmetic operations (+, -, *, /, %, divmod(), pow(),
**, <<, >>, &, ^, |) with reflected (swapped) operands.
These functions are only called if the left operand
does not support the corresponding operation. For
instance, to evaluate the expression x-y, where y is an
instance of a class that has an __rsub__() method,
y.__rsub__(x) is called."

This code demonstrates the correct behavior and then
the problem:

class A(object):
    def __radd__(self, other):
        return '__radd__', other

print None + A()
print A() + A()

giving....

('__radd__', None)

Traceback (most recent call last):
  File "C:/Temp/reflectedbug.py", line 6, in -toplevel-
    print A() + A()
TypeError: unsupported operand type(s) for +: 'A' and 'A'

I've replaced None in the first print statement with
many kinds of builtin objects, instances of other
classes, and with instances of subclasses of A.  In all
these cases the __radd__ operator is used as
documented.  I've only seen the problem when the two
operands are of the same type.

This problem also occurs during the backing-off to
plain operators that occurs when augmented operators,
e.g. __iadd__, aren't implemented by the type and the
operands are of the same type.

This problem is present in 2.4 on Linux and Windows,
and in the current CVS version (2.5a0, 27-Feb-05) on Linux.
msg24406 - (view) Author: Hugh Secker-Walker (hughsw) Date: 2005-02-28 01:31
Logged In: YES 
user_id=1146279

Someone remove this accidental repost.  Thanks.
History
Date User Action Args
2022-04-11 14:56:09adminsetgithub: 41632
2005-02-28 01:23:12hughswcreate