[Numpy-discussion] Read only array?

Todd Miller jmiller at stsci.edu
Sat May 22 04:02:01 CDT 2004


On Fri, 2004-05-21 at 23:05, Shin, Daehyok wrote:
> I am wondering if there is any way to set an array as read-only,
> so that any trial to modify values of elements in the array raises some
> warning.
> Is it a cool feature to prevent unexpected side effect?
> 
> Daehyok Shin (Peter)
> 

In numarray you can do this:

>>> from numarray import *
>>> def make_readonly(a):
..     v = a.view()
..     s = a.tostring()
..     v._data = s
..     return v
..
>>> a = arange(100)
>>> b = make_readonly(a)
>>> b[0] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: NA_setFromPythonScalar: assigment to readonly array buffer

This works because of the buffer protocol and the fact that a string is
a read-only buffer.  Using the buffer protocol is a numarray feature so
I'm pretty sure Numeric can't do this.  Also note that in C, this
read-only array is actually writable.

Regards,
Todd





More information about the Numpy-discussion mailing list