When the value of an attribute changes, other parts of the program might need to be notified that the change has occurred. The Traits package makes this possible for trait attributes. This functionality lets you write programs using the same, powerful event-driven model that is used in writing user interfaces and for other problem domains.
Requesting trait attribute change notifications can be done in several ways:
- Dynamically, by calling on_trait_change() or on_trait_event() to establish (or remove) change notification handlers.
- Statically, by decorating methods on the class with the @on_trait_change decorator to indicate that they handle notification for specified attributes.
- Statically, by using a special naming convention for methods on the class to indicate that they handle notifications for specific trait attributes.
Dynamic notification is useful in cases where a notification handler cannot be defined on the class (or a subclass) whose trait attribute changes are to be monitored, or if you want to monitor changes on certain instances of a class, but not all of them. To use dynamic notification, you define a handler method or function, and then invoke the on_trait_change() or on_trait_event() method to register that handler with the object being monitored. Multiple handlers can be defined for the same object, or even for the same trait attribute on the same object. The handler registration methods have the following signatures:
on_trait_change(handler[, name=None, remove=False, dispatch='same'])¶
on_trait_event(handler[, name=None, remove=False, dispatch='same'])¶
In these signatures:
- handler: Specifies the function or bound method to be called whenever the trait attributes specified by the name parameter are modified.
- name: Specifies trait attributes whose changes trigger the handler being called. If this parameter is omitted or is None, the handler is called whenever any trait attribute of the object is modified. The syntax supported by this parameter is discussed in The name Parameter.
- remove: If True (or non-zero), then handler will no longer be called when the specified trait attributes are modified. In other words, it causes the handler to be “unhooked”.
- dispatch: String indicating the thread on which notifications must be run. In most cases, it can be omitted. See the Traits API Reference for details on non-default values.
Example of a Dynamic Notification Handler¶
Setting up a dynamic trait attribute change notification handler is illustrated in the following example:
# dynamic_notification.py --- Example of dynamic notification from traits.api import Float, HasTraits, Instance class Part (HasTraits): cost = Float(0.0) class Widget (HasTraits): part1 = Instance(Part) part2 = Instance(Part) cost = Float(0.0) def __init__(self): self.part1 = Part() self.part2 = Part() self.part1.on_trait_change(self.update_cost, 'cost') self.part2.on_trait_change(self.update_cost, 'cost') def update_cost(self): self.cost = self.part1.cost + self.part2.cost # Example: w = Widget() w.part1.cost = 2.25 w.part2.cost = 5.31 print w.cost # Result: 7.56
In this example, the Widget constructor sets up a dynamic trait attribute change notification so that its update_cost() method is called whenever the cost attribute of either its part1 or part2 attribute is modified. This method then updates the cost attribute of the widget object.
The name Parameter¶
The name parameter of on_trait_change() and on_trait_event() provides significant flexibility in specifying the name or names of one or more trait attributes that the handler applies to. It supports syntax for specifying names of trait attributes not just directly on the current object, but also on sub-objects referenced by the current object.
The name parameter can take any of the following values:
- Omitted, None, or ‘anytrait’: The handler applies to any trait attribute on the object.
- A name or list of names: The handler applies to each trait attribute on the object with the specified names.
- An “extended” name or list of extended names: The handler applies to each trait attribute that matches the specified extended names.
Extended names use the following syntax:
xname ::= xname2['.'xname2]* xname2 ::= ( xname3 | '['xname3[','xname3]*']' ) ['*'] xname3 ::= xname | ['+'|'-'][name] | name['?' | ('+'|'-')[name]]
A name is any valid Python attribute name.
Semantics of extended name notation
|item1.item2||A trait named item1 contains an object (or objects, if item1 is a list or dictionary), with a trait named item2. Changes to either item1 or item2 trigger a notification.|
|item1:item2||A trait named item1 contains an object (or objects, if item1 is a list or dictionary), with a trait named item2. Changes to item2 trigger a notification, while changes to item1 do not (i.e., the ‘:’ indicates that changes to the link object are not reported.|
|[item1, item2, …, itemN]||A list that matches any of the specified items. Note that at the topmost level, the surrounding square brackets are optional.|
|item||A trait named item is a list. Changes to item or to its members triggers a notification.|
|name?||If the current object does not have an attribute called name, the reference can be ignored. If the ‘?’ character is omitted, the current object must have a trait called name; otherwise, an exception is raised.|
|prefix+||Matches any trait attribute on the object whose name begins with prefix.|
|+metadata_name||Matches any trait on the object that has a metadata attribute called metadata_name.|
|-metadata_name||Matches any trait on the current object that does not have a metadata attribute called metadata_name.|
|prefix+metadata_name||Matches any trait on the object whose name begins with prefix and that has a metadata attribute called metadata_name.|
|prefix-metadata_name||Matches any trait on the object whose name begins with prefix and that does not have a metadata attribute called metadata_name.|
||Matches all traits on the object.|
|pattern*||Matches object graphs where pattern occurs one or more times. This option is useful for setting up listeners on recursive data structures like trees or linked lists.|
Examples of extended name notation
||Matches object.foo, object.bar, and object.baz.|
||Matches object.foo.bar and object.foo.baz|
||Matches a list trait on object named foo.|
||Matches the name trait of each tree node object that is linked from the left or right traits of a parent node, starting with the current object as the root node. This pattern also matches the name trait of the current object, as the left and right modifiers are optional.|
||Matches any trait on the current object that has a metadata attribute named dirty set.|
||Matches any trait on object.foo that has a metadata attribute named dirty set.|
||Matches object.foo.bar or any trait on object.foo that does not have a metadata attribute named dirty set.|
For a pattern that references multiple objects, any of the intermediate
(non-final) links can be traits of type Instance, List, or Dict. In the case of
List or Dict traits, the subsequent portion of the pattern is applied to each
item in the list or value in the dictionary. For example, if self.children
is a list, a handler set for
'children.name' listens for changes to the
name trait for each item in the self.children list.
The handler routine is also invoked when items are added or removed from a list or dictionary, because this is treated as an implied change to the item’s trait being monitored.
Notification Handler Signatures¶
The handler passed to on_trait_change() or on_trait_event() can have any one of the following signatures:
- handler(name, new)
- handler(object, name, new)
- handler(object, name, old, new)
These signatures use the following parameters:
- object: The object whose trait attribute changed.
- name: The attribute that changed. If one of the objects in a sequence is a
List or Dict, and its membership changes, then this is the name of the trait
that references it, with ‘_items appended. For example, if the handler is
'foo.bar.baz', where bar is a List, and an item is added to bar, then the value of the name parameter is ‘bar_items’.
- new: The new value of the trait attribute that changed. For changes to List and Dict objects, this is a list of items that were added.
- old: The old value of the trait attribute that changed. For changes to List and Dict object, this is a list of items that were deleted. For event traits, this is Undefined.
If the handler is a bound method, it also implicitly has self as a first argument.
Dynamic Handler Special Cases¶
In the one- and two-parameter signatures, the handler does not receive enough information to distinguish between a change to the final trait attribute being monitored, and a change to an intermediate object. In this case, the notification dispatcher attempts to map a change to an intermediate object to its effective change on the final trait attribute. This mapping is only possible if all the intermediate objects are single values (such as Instance or Any traits), and not List or Dict traits. If the change involves a List or Dict, then the notification dispatcher raises a TraitError when attempting to call a one- or two-parameter handler function, because it cannot unambiguously resolve the effective value for the final trait attribute.
Zero-parameter signature handlers receive special treatment if the final trait attribute is a List or Dict, and if the string used for the name parameter is not just a simple trait name. In this case, the handler is automatically called when the membership of a final List or Dict trait is changed. This behavior can be useful in cases where the handler needs to know only that some aspect of the final trait has changed. For all other signatures, the handler function must be explicitly set for the name_items trait in order to called when the membership of the name trait changes. (Note that the prefix+ and item syntaxes are both ways to specify both a trait name and its ‘_items’ variant.)
This behavior for zero-parameter handlers is not triggered for simple trait names, to preserve compatibility with code written for versions of Traits prior to 3.0. Earlier versions of Traits required handlers to be separately set for a trait and its items, which would result in redundant notifications under the Traits 3.0 behavior. Earlier versions also did not support the extended trait name syntax, accepting only simple trait names. Therefore, to use the “new style” behavior of zero-parameter handlers, be sure to include some aspect of the extended trait name syntax in the name specifier.
# list_notifier.py -- Example of zero-parameter handlers for an object # containing a list from traits.api import HasTraits, List class Employee: pass class Department( HasTraits ): employees = List(Employee) def a_handler(): print "A handler" def b_handler(): print "B handler" def c_handler(): print "C handler" fred = Employee() mary = Employee() donna = Employee() dept = Department(employees=[fred, mary]) # "Old style" name syntax # a_handler is called only if the list is replaced: dept.on_trait_change( a_handler, 'employees' ) # b_handler is called if the membership of the list changes: dept.on_trait_change( b_handler, 'employees_items') # "New style" name syntax # c_handler is called if 'employees' or its membership change: dept.on_trait_change( c_handler, 'employees' ) print "Changing list items" dept.employees = donna # Calls B and C print "Replacing list" dept.employees = [donna] # Calls A and C
The static approach is the most convenient option, but it is not always possible. Writing a static change notification handler requires that, for a class whose trait attribute changes you are interested in, you write a method on that class (or a subclass). Therefore, you must know in advance what classes and attributes you want notification for, and you must be the author of those classes. Static notification also entails that every instance of the class has the same notification handlers.
To indicate that a particular method is a static notification handler for a particular trait, you have two options:
- Apply the @on_trait_change decorator to the method.
- Give the method a special name based on the name of the trait attribute it “listens” to.
The most flexible method of statically specifying that a method is a notification handler for a trait is to use the @on_trait_change() decorator. The @on_trait_change() decorator is more flexible than specially-named method handlers, because it supports the very powerful extended trait name syntax (see The name Parameter). You can use the decorator to set handlers on multiple attributes at once, on trait attributes of linked objects, and on attributes that are selected based on trait metadata.
The syntax for the decorator is:
@on_trait_change( 'extended_trait_name' ) def any_method_name( self, ...): ...
In this case, extended_trait_name is a specifier for one or more trait attributes, using the syntax described in The name Parameter.
The signatures that are recognized for “decorated” handlers are the same as those for dynamic notification handlers, as described in Notification Handler Signatures. That is, they can have an object parameter, because they can handle notifications for trait attributes that do not belong to the same object.
The functionality provided by the @on_trait_change() decorator is identical to that of specially-named handlers, in that both result in a call to on_trait_change() to register the method as a notification handler. However, the two approaches differ in when the call is made. Specially-named handlers are registered at class construction time; decorated handlers are registered at instance creation time, prior to setting any object state.
A consequence of this difference is that the @on_trait_change() decorator causes any default initializers for the traits it references to be executed at instance construction time. In the case of specially-named handlers, any default initializers are executed lazily.
Specially-named Notification Handlers¶
There are two kinds of special method names that can be used for static trait attribute change notifications. One is attribute-specific, and the other applies to all trait attributes on a class.
To notify about changes to a single trait attribute named name, define a method named _name_changed() or _name_fired(). The leading underscore indicates that attribute-specific notification handlers are normally part of a class’s private API. Methods named _name_fired() are normally used with traits that are events, described in Trait Events.
To notify about changes to any trait attribute on a class, define a method named _anytrait_changed().
Both of these types of static trait attribute notification methods are illustrated in the following example:
# static_notification.py --- Example of static attribute # notification from traits.api import HasTraits, Float class Person(HasTraits): weight_kg = Float(0.0) height_m = Float(1.0) bmi = Float(0.0) def _weight_kg_changed(self, old, new): print 'weight_kg changed from %s to %s ' % (old, new) if self.height_m != 0.0: self.bmi = self.weight_kg / (self.height_m**2) def _anytrait_changed(self, name, old, new): print 'The %s trait changed from %s to %s ' \ % (name, old, new) """ >>> bob = Person() >>> bob.height_m = 1.75 The height_m trait changed from 1.0 to 1.75 >>> bob.weight_kg = 100.0 The weight_kg trait changed from 0.0 to 100.0 weight_kg changed from 0.0 to 100.0 The bmi trait changed from 0.0 to 32.6530612245 """
In this example, the attribute-specific notification function is _weight_kg_changed(), which is called only when the weight_kg attribute changes. The class-specific notification handler is _anytrait_changed(), and is called when weight_kg, height_m, or bmi changes. Thus, both handlers are called when the weight_kg attribute changes. Also, the _weight_kg_changed() function modifies the bmi attribute, which causes _anytrait_changed() to be called for that attribute.
The arguments that are passed to the trait attribute change notification method depend on the method signature and on which type of static notification handler it is.
Attribute-specific Handler Signatures¶
For an attribute specific notification handler, the method signatures supported are:
_name_changed(name, old, new)
The method name can also be _name_fired(), with the same set of signatures.
In these signatures:
- new is the new value assigned to the trait attribute. For List and Dict objects, this is a list of the items that were added.
- old is the old value assigned to the trait attribute. For List and Dict objects, this is a list of the items that were deleted.
- name is the name of the trait attribute. The extended trait name syntax is not supported. 
Note that these signatures follow a different pattern for argument interpretation from dynamic handlers and decorated static handlers. Both of the following methods define a handler for an object’s name trait:
def _name_changed( self, arg1, arg2, arg3): pass @on_trait_change('name') def some_method( self, arg1, arg2, arg3): pass
However, the interpretation of arguments to these methods differs, as shown in the following table.
Handler argument interpretation
General Static Handler Signatures¶
In the case of a non-attribute specific handler, the method signatures supported are:
_anytrait_changed(name, old, new)
The meanings for name, new, and old are the same as for attribute-specific notification functions.
The Traits package defines a special type of trait called an event. Events are instances of (subclasses of) the Event class.
There are two major differences between a normal trait and an event:
- All notification handlers associated with an event are called whenever any value is assigned to the event. A normal trait attribute only calls its associated notification handlers when the previous value of the attribute is different from the new value being assigned to it.
- An event does not use any storage, and in fact does not store the values assigned to it. Any value assigned to an event is reported as the new value to all associated notification handlers, and then immediately discarded. Because events do not retain a value, the old argument to a notification handler associated with an event is always the special Undefined object (see Undefined Object). Similarly, attempting to read the value of an event results in a TraitError exception, because an event has no value.
As an example of an event, consider:
# event.py --- Example of trait event from traits.api import Event, HasTraits, List, Tuple point_2d = Tuple(0, 0) class Line2D(HasTraits): points = List(point_2d) line_color = RGBAColor('black') updated = Event def redraw(self): pass # Not implemented for this example def _points_changed(self): self.updated = True def _updated_fired(self): self.redraw()
In support of the use of events, the Traits package understands attribute-specific notification handlers with names of the form _name_fired(), with signatures identical to the _name_changed() functions. In fact, the Traits package does not check whether the trait attributes that _name_fired() handlers are applied to are actually events. The function names are simply synonyms for programmer convenience.
Similarly, a function named on_trait_event() can be used as a synonym for on_trait_change() for dynamic notification.
Python defines a special, singleton object called None. The Traits package introduces an additional special, singleton object called Undefined.
The Undefined object is used to indicate that a trait attribute has not yet had a value set (i.e., its value is undefined). Undefined is used instead of None, because None is often used for other meanings, such as that the value is not used. In particular, when a trait attribute is first assigned a value and its associated trait notification handlers are called, Undefined is passed as the value of the old parameter to each handler, to indicate that the attribute previously had no value. Similarly, the value of a trait event is always Undefined.
|||For List and Dict trait attributes, you can define a handler with the name _name_items_changed(), which receives notifications of changes to the contents of the list or dictionary. This feature exists for backward compatibility. The preferred approach is to use the @on_trait_change decorator with extended name syntax. For a static _name_items_changed() handler, the new parameter is a TraitListEvent or TraitDictEvent whose index, added, and removed attributes indicate the nature of the change, and the old parameter is Undefined.|