[Numpy-discussion] Setter on array

Christian K. ckkart@hoc....
Fri Aug 16 07:33:38 CDT 2013


Hi Hugo,

Am 14.08.13 10:34, schrieb Hugo Gagnon:
> What is the best way, if any, to "do something" whenever array elements
> are changed in-place?  For example, if I have a = arange(10), then
> setting a[3] = 1 would, say, call a function automatically.

a one made a simple subclass of ndarray which takes a callback argument 
and which should do exactly what you are asking for. I am not an expert 
so you might want to try to understand the concerns mentioned in the 
other answers.

class cbarray(N.ndarray):
     def __new__(subtype, data, cb=None, dtype=None, copy=False):
         subtype.__defaultcb = cb

         if copy:
             data = N.array(data,dtype=dtype)
         else:
             data = N.asarray(data,dtype=dtype)

         data = data.view(subtype)
         return data

     def _notify(self):
         if self.cb is not None:
             self.cb()

     def _get_shape(self):
         return super(cbarray, self).shape
     shape = property(_get_shape)

     def __setitem__(self, item, val):
         N.ndarray.__setitem__(self, item, val)
         self._notify()

     def __array_finalize__(self,obj):
         if not hasattr(self, "cb"):
             # The object does not yet have a `.cb` attribute
             self.cb = getattr(obj,'cb',self.__defaultcb)

     def __reduce__(self):
         object_state = list(N.ndarray.__reduce__(self))
         subclass_state = (self.cb,)
         object_state[2] = (object_state[2],subclass_state)
         return tuple(object_state)

     def __setstate__(self,state):
         nd_state, own_state = state
         N.ndarray.__setstate__(self,nd_state)

         cb, = own_state
         self.cb = cb


Regards, Christian




More information about the NumPy-Discussion mailing list