Immutable numpy array?

PythonArraysNumpyImmutabilityReadonly

Python Problem Overview


Is there a simple way to create an immutable NumPy array?

If one has to derive a class from ndarray to do this, what's the minimum set of methods that one has to override to achieve immutability?

Python Solutions


Solution 1 - Python

You can make a numpy array unwriteable:

a = np.arange(10)
a.flags.writeable = False
a[0] = 1
# Gives: ValueError: assignment destination is read-only

Also see the discussion in this thread:

http://mail.scipy.org/pipermail/numpy-discussion/2008-December/039274.html

and the documentation:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html

Solution 2 - Python

I have a subclass of Array at this gist: https://gist.github.com/sfaleron/9791418d7023a9985bb803170c5d93d8

It makes a copy of its argument and marks that as read-only, so you should only be able to shoot yourself in the foot if you are very deliberate about it. My immediate need was for it to be hashable, so I could use them in sets, so that works too. It isn't a lot of code, but about 70% of the lines are for testing, so I won't post it directly.

Note that it's not a drop-in replacement; it won't accept any keyword args like a normal Array constructor. Instances will behave like Arrays, though.

Solution 3 - Python

Setting the flag directly didn't work for me, but using ndarray.setflags did work:

a = np.arange(10)
a.setflags(write=False)
a[0] = 1  # ValueError

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNPEView Question on Stackoverflow
Solution 1 - PythonJoshAdelView Answer on Stackoverflow
Solution 2 - PythonsfaleronView Answer on Stackoverflow
Solution 3 - PythonKrisView Answer on Stackoverflow