[Numpy-discussion] Checking for views (was: Should arr.diagonal() return a copy or aview?)

Robert Kern robert.kern at gmail.com
Thu May 24 12:52:09 EDT 2012

On Thu, May 24, 2012 at 4:10 PM, Nathaniel Smith <njs at pobox.com> wrote:
> On Thu, May 24, 2012 at 3:56 PM, Jonathan T. Niehof <jniehof at lanl.gov> wrote:
>> On 05/23/2012 05:31 PM, T J wrote:
>>> It seems that there are a number of ways to check if an array is a view.
>>> Do we have a preferred way in the API that is guaranteed to stay
>>> available? Or are all of the various methods "here to stay"?
>> We've settled on checking array.base, which I think was the outcome of a
>> stackoverflow thread that I can't dig up. (I'll check with the guy who
>> wrote the code.)
> The problem is that "is a view" isn't a very meaningful concept...
> checking .base will tell you whether writes to an array are likely to
> affect some object that existed before that array was created. But it
> doesn't tell you whether writes to that array can affect any
> *particular* other object (at least without a fair amount of groveling
> around the innards of both objects), and it can happen that an object
> has base == None yet writes to it will affect another object, and it
> can happen that an object has base != None and yet writes to it won't
> affect any object that was ever accessible to your code. AFAICT it's
> really these other questions that one would like to answer, and
> checking .base won't answer them.

numpy.may_share_memory() gets closer, but it can be defeated by
certain striding patterns. At least, it is conservative and reports
false positives but not false negatives. Implementing
numpy.does_share_memory() correctly involves some number theory and
hairy edge cases.

(Hmm, now that I think about it, the edge cases are when the strides
are 0 or negative. 0-stride axes can simply be removed, and I think we
should be able to work back to a first item and flip the sign on the
negative strides. The typical positive-stride solution can be found in
an open source C++ global array code, IIRC. Double-hmmm...)

Robert Kern

More information about the NumPy-Discussion mailing list