Triggering an event in a Python feature package when an Array element changes

I am using the Python trait set, and I am trying to figure out the correct way to use the traits.trait_numeric.Array class. Directly write a subclass of traits.api.HasTraits with the sign of an array, so when Array changes, on_trait_change is fired, but I can’t figure out how to trigger any event when the elements of the array are changed in place. Here is a minimal example:

from traits.api import HasTraits from traits.trait_numeric import Array import numpy as np class C(HasTraits): x = Array def __init__(self): self.on_trait_event(self.do_something, 'x') def do_something(self): print 'Doing something' c = C() # This line calls do_something() cx = np.linspace(0,1,10) # This one doesn't, and I wish it did cx[3] = 100 # Same with this one cx[:] = np.ones(cxshape) 

I hope there is some built-in function traits.trait_numeric.Array that I do not know about, since detecting when a part of the array has changed seems to be very standard what is needed.

Denying this, I think the problem can be resolved by creating a custom attribute class that also inherits numpy.array and then changes the [] operator so that it explicitly calls the correct attribute event types. But I hope this may be a worm that I don’t have to open.

+4
source share
1 answer

I am afraid that this is really impossible. numpy arrays see raw memory. All of this can change this memory without going through a numpy array object. Usually we use a template to reassign the entire array after performing a slice / index assignment.

 import numpy as np from traits.api import Array, HasTraits, NO_COMPARE class C(HasTraits): x = Array(comparison_mode=NO_COMPARE) def _x_changed(self): print 'Doing something' c = C() cx = np.linspace(0, 1, 10) # This does not trigger: cx[3] = 100 # This does: cx = cx 
+8
source

Source: https://habr.com/ru/post/1500213/


All Articles