[Numpy-discussion] immutable numpy arrays

Geoffrey Irving irving@naml...
Wed Dec 17 15:52:02 CST 2008

Currently numpy arrays are either writable or unwritable, but
unwritable arrays can still be changed through other copies.  This
means that when a numpy array is passed into an interface that
requires immutability for safety reasons, a copy always has to be

One way around this would be to add a NPY_IMMUTABLE flag signifying
that the contents of the array will never change through other copies.
 This flag would be in addition to the current NPY_WRITEABLE flag, so
it would be fully backwards compatible.  The flag would be propagated
along slices and views.

For example, a numpy array created from C code that guarantees
immutability would have the flag set.  If the array was passed back
into a function that required an immutable array, the code could check
the immutable flag and skip the copy.  This behavior could also be
used to implement safe copy-on-write semantics.

Making this more generally useful would probably require additional
flags to document whether a writeable copy of the array might exists
(something like NPY_LEAKED) in order to avoid copies for newly created
writeable arrays.

Has the issue of immutability been considered before?  It seems like a
basic NPY_IMMUTABLE flag would be fairly easy to add without backwards
compatibility issues, but the secondary features such as NPY_LEAKED
would be more complicated.


More information about the Numpy-discussion mailing list