Why do operators and methods of built-in types differ

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Jan 31 07:40:06 EST 2009


En Sat, 31 Jan 2009 09:51:35 -0200, Csaba Hoch <csaba.hoch at gmail.com>  
escribió:

> if I write the following:
>
>     >>> 1+1
>     2
>
> it seems to be exactly equivalent to this:
>
>     >>> (1).__add__(1)
>     2
>
> However, if I write invalid code and try to add a list to an int, the
> errors will be different:
>
>     >>> 1+[]
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     TypeError: unsupported operand type(s) for +: 'int' and 'list'
>
>     >>> (1).__add__([])
>     NotImplemented
>
> I found that operator.__add__(1, []) gives the same result as 1+[].
>
> What is the reason behind this difference between the __add__ operator
> and int.__add__?

The operator "+" does more than blindy calling left.__add__(right). In  
this case, as int + list returns NotImplemented, it reverses the operands  
and tries right.__radd__(left), and only then it gives up and raises  
TypeError.

The actual rules are a bit more complex, involving type conversion too;  
see http://docs.python.org/reference/datamodel.html#emulating-numeric-types

-- 
Gabriel Genellina




More information about the Python-list mailing list