Stefan Behnel wrote: > Dag Sverre Seljebotn wrote: >>> # Some ways of multiplying all elements with 2 >>> x *= 2 >>> x[...] *= 2 >>> x[:,:] *= 2 >>> x += x >>> x[...] += x >> OK I'll make an exception here -- I'm willing to discuss whether we >> should depart from NumPy semantics here and let >> >> x2 = x >> x *= 2 >> >> allocate new memory, so that x2 is not modified, being consistent with a >> direct transformation to "x = x * 2". One can always write >> >> x[...] *= 2 >> >> if one wishes to modify original memory. > > What's wrong with > > x = 2 * x2 > > for doing a copy ? > > x *= 2 > > pretty clearly states that I want to modify x in place.
The problem is that if you do y = x x *= 2 then in current NumPy, y and x will still point to the same memory and reference the same values (in fact, be the exact same view object). Usual Python semantics seems to imply that what NumPy *should* have done is let the latter line mean "x = x * 2", where a new array is allocated and the value of x*2 copied into the new array, so that x and y points to different memory after the operation. BTW, something I forgot to say about the == operator is that a common pattern is to do x[x == 2] = 0 to replace 2 with 0 everywhere in x, that's one of its primary uses. To make it more clear: xeq2mask = (x == 2) # array of booleans x[xeq2mask] = 0 (That is connected with the boolean indexing thing, which I'm vary about letting into Cython, although an exception can safely be made in the case of __setitem__). -- Dag Sverre _______________________________________________ Cython-dev mailing list [email protected] http://codespeak.net/mailman/listinfo/cython-dev
