[Numpy-discussion] array copy-to-self and views
Thu Feb 1 03:07:29 CST 2007
On 01/02/07, Zachary Pincus <firstname.lastname@example.org> wrote:
> I recently was trying to write code to modify an array in-place (so
> as not to invalidate any references to that array) via the standard
> python idiom for lists, e.g.:
You can do this, but if your concern is invalidating references, you
might want to think about rearranging your application so you can just
return "new" arrays (that may share elements), if that is possible.
> a[:] = numpy.flipud(a)
> Now, flipud returns a view on 'a', so assigning that to 'a[:]'
> provides pretty strange results as the buffer that is being read (the
> view) is simultaneously modified. Here is an example:
> A question, then: Does this represent a bug? Or perhaps there is a
> better idiom for modifying an array in-place than 'a[:] = ...'? Or is
> incumbent on the user to ensure that any time an array is directly
> modified, that the modifying array is not a view of the original array?
It's the user's job to keep them separate. Sorry. If you're worried -
say if it's an array you don't have much control over (so it might
share elements without you knowing), you can either return a new
array, or if you must modify it in place, copy the right-hand side
before using it (a[:]=flipud(a).copy()).
It would in principle be possible for numpy to provide a function that
tells you if two arrays might share data (simply compare the pointer
to the malloc()ed storage and ignore strides and offset; a bit
conservative but probably Good Enough, though a bit more cleverness
should let one get the Right Answer efficiently).
Anne M. Archibald
More information about the Numpy-discussion