[Numpy-discussion] The future of ndarray.diagonal()

Matthew Brett matthew.brett at gmail.com
Sat Jan 3 16:55:38 EST 2015


Hi,

On Thu, Jan 1, 2015 at 9:35 PM, Alexander Belopolsky <ndarray at mac.com> wrote:
> A discussion [1] is currently underway at GitHub which will benefit from a
> larger forum.
>
> In version 1.9, the diagonal() method was changed to return a read-only
> (non-contiguous) view into the original array instead of a plain copy.
> Also, it has been announced [2] that in 1.10 the view will become
> read/write.
>
> A concern has now been raised [3] that this change breaks backward
> compatibility too much.
>
> Consider the following code:
>
> x = numy.eye(2)
> d = x.diagonal()
> d[0] = 2
>
> In 1.8, this code runs without errors and results in [2, 1] stored in array
> d.  In 1.9, this is an error.  With the current plan, in 1.10 this will
> become valid again, but the result will be different: x[0,0] will be 2 while
> it is 1 in 1.8.
>
> Two alternatives  are suggested for discussion:
>
> 1. Add copy=True flag to diagonal() method.
> 2. Roll back 1.9 change to diagonal() and introduce an additional
> diagonal_view() method to return a view.

I think this point is a good one, from Konrad Hinsen's blog post:

<quote>
If you get a Python script, say as a reviewer for a submitted article,
and see “import numpy”, you don’t know which version of numpy the
authors had in mind. If that script calls array.diag() and modifies
the return value, does it expect to modify a copy or a view? The
result is very different, but there is no way to tell. It is possible,
even quite probable, that the code would execute fine with both NumPy
1.8 and the upcoming NumPy 1.10, but yield different results.
</quote>

That rules out the current 1.10 plan I think.

copy=True as default seems like a nice compact and explicit solution to me.

Cheers,

Matthew



More information about the NumPy-Discussion mailing list