Skip to content

Instantly share code, notes, and snippets.

@sfaleron
Last active June 6, 2025 16:19
Show Gist options
  • Save sfaleron/9791418d7023a9985bb803170c5d93d8 to your computer and use it in GitHub Desktop.
Save sfaleron/9791418d7023a9985bb803170c5d93d8 to your computer and use it in GitHub Desktop.
Immutable/hashable numpy Array
# ISC License (ISC)
#
# Copyright 2021 Christopher Fuller
#
# Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice appear in all copies.
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
from numpy import ndarray, asarray
class ImmutArray(ndarray):
"""https://numpy.org/doc/stable/user/basics.subclassing.html
>>> import numpy as np
>>> a=np.arange(4)
>>> ia=ImmutArray(a)
>>> (ia==[0,1,2,3]).all().item()
True
>>> (ia==(0,1,2,3)).all().item()
True
>>> ((0,1,2,3)==ia).all().item()
True
>>> ([0,1,2,3]==ia).all().item()
True
>>> (ia==range(4)).all().item()
True
>>> (range(4)==ia).all().item()
True
>>> a[1]=-1
>>> a
array([ 0, -1, 2, 3])
>>> (a==ia).all().item()
False
>>> (ia==a).all().item()
False
>>> ia[1]=-1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: assignment destination is read-only
>>> ia
ImmutArray([0, 1, 2, 3])
>>> (np.arange(4)==ia).all().item()
True
>>> (ia==np.arange(4)).all().item()
True
>>> ib=ia[1:3]
>>> ib
ImmutArray([1, 2])
>>> ib[0]=9
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: assignment destination is read-only
>>> ia=np.arange(4).view(ImmutArray)
>>> ia[0]=9
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: assignment destination is read-only
"""
def __new__(cls, arr):
obj = asarray(arr).copy().view(cls)
obj.flags.writeable = False
obj._hash = cls._gethash(obj)
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self._hash = getattr(obj, '_hash', None) or self._gethash(obj)
self.flags.writeable = False
@staticmethod
def _gethash(arr):
return hash((arr.shape, tuple(arr.flat)))
def __hash__(self):
return self._hash
__eq__ = ndarray.__eq__
if __name__ == '__main__':
import doctest
results = doctest.testmod()
if results.attempted:
if results.failed:
print('Failure!')
else:
print('Success!')
else:
print('No tests found!')
@sfaleron
Copy link
Author

Previous version (rev2, only posted for about a week) implemented eq() with a scalar True/False result, rather than element-wise, as is usual for NumPy arrays.
This version delegates to the parent class, but a wrinkle arises: Some (or all) methods/ufuncs are returning scalars wrapped in the array type rather than the bare scalar, as would be expected, at least for the all() methods I use in the tests.
I'd like to clean that up, but I probably won't spend a lot of time on it.

@diegojromerolopez
Copy link

Dear @sfaleron

What is the license of this code?

@sfaleron
Copy link
Author

sfaleron commented Nov 5, 2021

I gravitate to APLv2, but for a single-file/snippet I may look for something less verbose. I'm a little shy about using public domain, there's some ambiguities and pitfalls there. Looks like I'll use https://opensource.org/licenses/ISC.

@eladn
Copy link

eladn commented Dec 25, 2023

Copying the array doesn't work.

@urob
Copy link

urob commented Jun 6, 2025

Copying the array doesn't work.

The same issue occurs for any array method that internally mutates some intermittent array, even if it eventually returns a new array/ImmutArray instance. This is because all operations on ImmutArrays create new ImmutArrays.

To some extend this is the expected behavior. E.g., we'd expect ib = ia + 1 to be immutable as well. I agree that it is irritating, however, if the mutation is on some intermittent array that's just an implementation detail.

Perhaps, a more useful version of this subclass would just return regular numpy arrays for all operations? That is, ImmutArrays would be one-off instances for which b = ia + 1 would yield a regular (writable) numpy array.

It depends on the usecase, of course, but my guess is that this would run into fewer edge cases. And if the user requires the output to be immutable as well, they could just recast it as ImmutArray.

Edit: It looks like it would be pretty hard to get operations on ImmutArrays to return regular numpy array:

For view casting and new-from-template, the equivalent of ndarray.__new__(MySubClass,... is called, at the C level.

@urob
Copy link

urob commented Jun 6, 2025

Oh, I think the hashing is broken:

>>> a = np.arange(4)
>>> ia = ImmutArray(a)
>>> hash(ia) == hash(ia + 1)
True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment