3

In Python 3.x, I'm working with large numpy arrays. I would like to have confirmation (without having to actually do some kind of experiment) that methods I have written are either working with a copy of the array OR are working with a direct reference to the array.

I would like confirmation also that the array in question has or has not been modified.

In C++, if I wanted to ensure that an object was NOT modified, I could pass it as a const... in Python, I seem to have no such assurances and have to be extra careful.

So, to sum up: I need a way to tell whether a copy has or has not been produced of a numpy array. I need a way to tell if an array (or any object for that matter) has been modified. I would prefer a fast, automatic way rather than having to do an experiment.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Trekkie
  • 964
  • 1
  • 9
  • 32
  • 2
    Both [(naive use of) `.base`](http://stackoverflow.com/questions/11286864/is-there-a-way-to-check-if-numpy-arrays-share-the-same-data#comment14852955_11286976) and [`.flags['OWNDATA']`](http://stackoverflow.com/q/28886731/190597) can lead to false conclusions. [According to NumPy developer Robert Kern](http://stackoverflow.com/a/10752605/190597), the best we have at the moment is `np.may_share_memory`. – unutbu Apr 02 '15 at 12:39

1 Answers1

8

You can use np.ndarray.flags:

>>> a = np.arange(5)
>>> a.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

For example, you can set an array to not be writeable, by using np.setflags; In that case an attempt to modify the array will fail:

>>> a.setflags(write=False)  # sets the WRITEABLE flag to False
>>> a[2] = 10                # the modification will fail
ValueError: assignment destination is read-only

Another useful flag is the OWNDATA, which for example can indicate that the array is in fact a view on another array, so does not own its data:

>>> a = np.arange(5)
>>> b = a[::2]
>>> a.flags['OWNDATA']
True
>>> b.flags['OWNDATA']
False
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
  • 1
    I wasn't aware that was possible. That is *really* useful. – TheBlackCat Apr 02 '15 at 11:33
  • @behzad.nouri That is great to know, thank you so much! I wonder if Python array types, e.g. list etc have such features? That would be super useful too. – Trekkie Apr 02 '15 at 12:55