I would like to create a read-only reference to a NumPy array. Is this a correct way to make b a read-only reference to a (a is any NumPy array)?
def get_readonly_view(a):
b = a.view()
b.flags.writeable = False
return b
Specifically, I would like to ensure the above does not 'copy' the contents of a? (I tried testing this with np.shares_memory and it does return True. But I am not sure if that is a correct test.)
In addition I wonder if get_readonly_view is already implemented in NumPy?
Update. It has been suggested to turn the array to a class property to make it read-only. I think this does not work:
import numpy as np
class Foo:
def __init__(self):
self._a = np.arange(15).reshape((3, 5))
@property
def a(self):
return self._a
def bar(self):
print(self._a)
But the client can change contents of _a:
>> baz = Foo()
>> baz.bar()
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
>> baz.a[1, 2] = 10
>> baz.bar()
[[ 0 1 2 3 4]
[ 5 6 10 8 9]
[10 11 12 13 14]]
while I would like baz.a[1, 2] = 10 to raise an exception.