Skip to content
Advertisement

How can I fire a Traits static event notification on a List?

I am working through the traits presentation from PyCon 2010. At about 2:30:45 the presenter starts covering trait event notifications, which allow (among other things) the ability to automatically call a subroutine any time a trait has changed.

I am running a modified copy of the example he gave… In this trial, I am trying to see whether I can fire a static event whenever I make a change to volume or volume_inputs.

JavaScript

Problem -> I never see any events from _volume_inputs_changed(). No matter what example I cook up, I can’t get a List to fire an event.

In the output below, there is no evidence that _volume_inputs_changed() ever fires.

JavaScript

Should a List() be able to fire a static List() event (such as _inputs_changed()) when using traits? If so, am I doing something wrong?

Advertisement

Answer

After browsing their unit tests, I found a test for Dict traits in enthought’s event unittest coverage

When you have a traits container like a traits.api.List() or traits.api.Dict(), you need to set up the magic event listener method name like this:

JavaScript
JavaScript

Likewise, I also discovered that the on_trait_change decorator (used for dynamic traits event notification) requires similar nomenclature if you are calling it with a traits.api.List or traits.api.Dict… so I could also write the code above as:

JavaScript

Either way, when I run the code, I get expected output:

JavaScript
Advertisement