[Numpy-discussion] numpy array change notifier?
Christan K.
ckkart@hoc....
Thu Oct 30 07:51:36 CDT 2008
Erik Tollerud <erik.tollerud <at> gmail.com> writes:
>
> Is there any straightforward way of notifying on change of a numpy
> array that leaves the numpy arrays still efficient?
>
You can instantiate the following ndarray derived class with a callable
argument. Any change to the data will call the callback function.
In [5]: def notify(arg):
...: print 'array changed'
...:
...:
In [6]: x = cbarray([1,2,3,4],cb=notify)
In [7]: x[2] = -1
array changed
alternatively I have used the pubsub module available as part of wxPython (see
the commented line in _notify())
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()
#Publisher().sendMessage(('changed'))
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 already 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
Hope thqat helps, Christian
More information about the Numpy-discussion
mailing list