[Python-Dev] binary operation heuristics -- bug or undocumented?

Alex A. Naanou alex.nanou at gmail.com
Fri Mar 19 13:46:07 CET 2010


A friend of mine stumbled upon the following behavior:


>>> class A(object): pass
>>> class B(object):
...     def __add__(self, other):
...         print 'B: adding B and %s objects.' % other.__class__.__name__
>>> class C(object):
...     def __radd__(self, other):
...         print 'C: adding C and %s objects.' % other.__class__.__name__
>>> a, b, c = A(), B(), C()

>>> b + c
B: adding B and C objects.

>>> a + c
C: adding C and A objects.

# so far, quite logical. now let's do this:

>>> 1 + c
C: adding C and int objects.


My first expectation would be to get a TypeError here, as ints indeed
have an __add__ method, and they do not know anything about C objects
(obviously :) ). On second thought, giving client code priority to
handle things has it's merits.

The problem is that I found no mention of this behavior in the docs.

P.S. tested in 2.5 through 3.0 and PyPy



More information about the Python-Dev mailing list