Suppose I have an array
that is an instance of subclassed from np.ndarray
class:
class RealisticInfoArray(np.ndarray):
def __new__(cls, input_array, info=None):
obj = np.asarray(input_array).view(cls)
obj.info = info
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'info', None)
def __reduce__(self):
print('in reduce')
# Get the parent's __reduce__ tuple
pickled_state = super(RealisticInfoArray, self).__reduce__()
# Create our own tuple to pass to __setstate__
new_state = pickled_state[2] + (self.info,)
# Return a tuple that replaces the parent's __setstate__ tuple with our own
return (pickled_state[0], pickled_state[1], new_state)
def __setstate__(self, state):
print('in set_state')
self.info = state[-1] # Set the info attribute
# Call the parent's __setstate__ with the other tuple elements.
super(RealisticInfoArray, self).__setstate__(state[0:-1])
def tofile(self, fid, sep="", format="%s"):
super().tofile(fid, sep, format)
print('in tofile')
def tobytes(self, order='C'):
super().tobytes(order)
print('in tobytes')
array = RealisticInfoArray(np.zeros((7, 9, 13)), info='tester')
Methods __reduce__
, __setstate__
, tofile
and tobytes
are included because I think they are involved in the saving that I want to perform: I want to store the array on disk (via any of the np.save
, np.savez
, np.savez_compressed
) and load it back while preserving the class of that object and all of the custom attributes.
I've already tried the approach of another SO question, but that is not working because I want to use np
functions, not pickle
or dill
. Also, I borrowed the subclass for MWE from there.
Another bit of information is that the actual saving is performed by np.lib.npyio.format.write_array
, which does not seem to allow any custom behavior of storing the data.
So, my question is whether it is possible to preserve the class of a stored array and if yes, how to do so?