[Numpy-discussion] Will transpose ever need to copy data?

Nathaniel Smith njs at pobox.com
Fri Jun 14 11:34:03 EDT 2013

On Wed, Jun 12, 2013 at 9:43 PM, Jaime Fernández del Río
<jaime.frio at gmail.com> wrote:
> On Wed, Jun 12, 2013 at 6:48 AM, Nathaniel Smith <njs at pobox.com> wrote:
>> Sounds like a doc bug. (Probably someone being over-careful -- the
>> default for many operations in numpy is that it's undefined whether
>> they return a view or not, so if it makes a difference to you you need
>> to take an explicit copy or similar.) Want to submit a PR to fix the
>> doc?
> Is it just in the function's docstring that the correction has to be made?
> I have also found a potential inconsistency related to this in np.rollaxis,
> the following examples should demonstrate it:
>>>> a = np.empty((2, 3))
>>>> b = np.transpose(a, (0, 1))
>>>> b.base is a
> True
>>>> c = np.rollaxis(a, 0, 1)
>>>> c.base is a
> False
>>>> c is a
> True
> It seems that np.transpose always returns a view of the passed array, while
> np.rollaxis either returns a view or the same array. I personally find this
> to be an annoying behavior: similarly to np.nonzero always returning a
> tuple, even when it holds a single item, this changing behavior can lead to
> hard to track bugs. Once you know what's going on, it is easy to work around
> by calling np.rollaxis on a[:] instead of a, but I doubt I will remember
> that the next time I need to use it.
> This is, by the way, also the behavior of np.ndarray.swapaxes, although it
> adds another degree of annoyance to the way it works:
>>>> d = a.swapaxes(0, 0)
>>>> d.base is a
> False
>>>> d is a
> True
>>>> e = a.swapaxes(0, -2)
>>>> e.base is a
> True
> I find that the right thing to do would be to eliminate the checks for
> special cases from both np.rollaxis and np.ndarray.swapaxes. The least would
> be, in np.ndarray.swapaxes, to move the check for equality of the axes to be
> swapped until after negative axis values have been dealt with. Should any of
> these changes be included in the doc change PR?

I agree that rollaxis and swapaxes should always return a either a
copy or a view, never the original array.

Ideally this would be a separate PR from the changes to the
np.transpose docs, because one or the other might turn out to take
more review iterations etc., but it's not the most critical thing



More information about the NumPy-Discussion mailing list