[Python-ideas] Fast sum() for non-numbers - why so much worries?
Oscar Benjamin
oscar.j.benjamin at gmail.com
Thu Jul 11 11:07:30 CEST 2013
On 10 July 2013 19:21, Joshua Landau <joshua at landau.ws> wrote:
>
> Python has previously had precedents where broken code does not get to
> dictate the language as long as that code was very rare. This is more
> than very rare. Additionally, Python does (unclearly, but it does do
> so) define __iadd__ to be an inplace version of __add__, so the code
> isn't just “broken” -- it's broken.
Although I'm quoting Joshua above, there are many people here who have
made the erroneous assertion that __iadd__ should always be equivalent
to __add__ and that there isn't much code that could be semantically
affected by the proposed change.
Numpy arrays treat += differently from + in the sense that a += b
coerces b to the same dtype as a and then adds in place whereas a + b
uses Python style type promotion. This behaviour is by design and it
is useful. It is also entirely appropriate (and not pathological) that
someone would use sum() to add numpy arrays.
An example where + and += give different results:
>>> from numpy import array
>>> a1 = array([1, 2, 3], dtype=int)
>>> a1
array([1, 2, 3])
>>> a2 = array([.5, .5, .5], dtype=float)
>>> a2
array([ 0.5, 0.5, 0.5])
>>> a1 + a2
array([ 1.5, 2.5, 3.5])
>>> a1 += a2
>>> a1
array([1, 2, 3])
Oscar
More information about the Python-ideas
mailing list