[Numpy-discussion] __iadd__(ndarray<int>, ndarray<float>)

Christopher Barker Chris.Barker@noaa....
Tue Mar 25 15:37:40 CDT 2008

Andreas Klöckner wrote:
>> [snip]
>> a += 3 is really equivalent to a = a+3. 
> Except when it isn't.

right -- it isn't the same. In fact, if I were king (or BDFL), you 
wouldn't be able to use += with immutable types, but I'm not ;-)

One of the reasons the augmented assignment operators where added to 
python was to provide a syntax for in-place operations. The other was to 
provide a quickie syntax for incrementing things. Unfortunately, those 
two aren't quite the same thing for immutable types.

Anyway, as far as numpy is concerned, it's very important that it means 
"in-place", and that means it won't change the type. Period. You simply 
have to know a bit more about types to use numpy than you do with the 
rest of Python, that that's be design.

In Numeric, there was far more default upcasting of data:

 >>> import Numeric
 >>> a = Numeric.array((1,2,3), Numeric.Float32)
 >>> a
array([ 1.,  2.,  3.],'f')
 >>> a + 1.2
array([ 2.2,  3.2,  4.2])

OOPS!  I just made a double array!

numpy has changed this default behavior, which is a good thing. It also 
changed the defaults of factories like ones() and zeros() for produce 
double arrays by default, so that for quickie use, users are more likely 
to get what they expect.


 > Complete loss of precision without warning is not a
> meaning that I, as a toolkit designer, would assign to an innocent-looking 
> inplace operation.

what about a Silent upcasting to a totally different type? That's an 
error too, if it's not what you intend.

> My hunch is that many people who start with Numpy will 
> spend an hour of their lives hunting a spurious bug caused by this. 

Maybe, but less time than spent finding the issues later caused by 
silent upcasting -- believe me, I spent a lot of time on that in the 
Numeric days.

Better to learn a bit about types early in your numpy career.


Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception


More information about the Numpy-discussion mailing list