| 1 |
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX |
| 2 |
# All rights reserved. |
| 3 |
# |
| 4 |
# This software is provided without warranty under the terms of the BSD |
| 5 |
# license included in LICENSE.txt and may be redistributed only under |
| 6 |
# the conditions described in the aforementioned license. The license |
| 7 |
# is also available online at http://www.enthought.com/licenses/BSD.txt |
| 8 |
# |
| 9 |
# Thanks for using Enthought open source! |
| 10 |
|
| 11 |
# --(on_trait_change Method Enhancements)-------------------------------------- |
| 12 |
r""" |
| 13 |
on_trait_change Method Enhancements |
| 14 |
=================================== |
| 15 |
|
| 16 |
In Traits 3.0, the capabilities of the **HasTraits** class's |
| 17 |
*on_trait_change* method has been greatly enhanced with the addition of a new |
| 18 |
*extended* trait name syntax for specifying the name of the trait the |
| 19 |
notification handler applies to. |
| 20 |
|
| 21 |
Previously, the trait name argument to the *on_trait_change* method could only |
| 22 |
be one of the following: |
| 23 |
|
| 24 |
Omitted, None, or 'anytrait' |
| 25 |
The notification handler applies to any trait on the object. |
| 26 |
|
| 27 |
name |
| 28 |
The notification handler applies to the trait on the object called *name*. |
| 29 |
|
| 30 |
[name1, ..., namen] |
| 31 |
The notification handler applies to each of the traits on the object with |
| 32 |
the specified names. |
| 33 |
|
| 34 |
In Traits 3.0, all of these forms are still supported, but now the syntax for |
| 35 |
specifying *name* has been expanded to allow a much broader set of traits that |
| 36 |
are *reachable* from the object the *on_trait_change* method is applied to. |
| 37 |
|
| 38 |
New *name* Parameter Syntax |
| 39 |
--------------------------- |
| 40 |
|
| 41 |
In Traits 3.0, the *name* parameter, in addition to being omitted, None or |
| 42 |
*anytrait*, can now be a single *xname* or a list of *xname* names, where |
| 43 |
an *xname* is an extended name of the form:: |
| 44 |
|
| 45 |
xname2['.'xname2]* |
| 46 |
|
| 47 |
An *xname2* is of the form:: |
| 48 |
|
| 49 |
(xname3 | '['xname3[','xname3]*']) ['*'] |
| 50 |
|
| 51 |
An *xname3* is of the form:: |
| 52 |
|
| 53 |
xname | ['+'|'-'][name] | name['?' | ('+'|'-')[name]] |
| 54 |
|
| 55 |
A *name* is any valid Python attribute name. The semantic meaning of this |
| 56 |
notation is as follows: |
| 57 |
|
| 58 |
[item, item, ..., item] |
| 59 |
A list which matches any of the specified items. Note that at the topmost |
| 60 |
level, the surrounding square brackets are optional. |
| 61 |
|
| 62 |
name? |
| 63 |
If the current object does not have an attribute called *name*, the |
| 64 |
reference can be ignored. If the '?' character is omitted, the current |
| 65 |
object must have a trait called *name*, otherwise an exception will be |
| 66 |
raised. |
| 67 |
|
| 68 |
prefix+ |
| 69 |
Matches any trait on the current object whose name begins with *prefix*. |
| 70 |
|
| 71 |
\+metadata_name |
| 72 |
Matches any trait on the current object having *metadata_name* metadata. |
| 73 |
|
| 74 |
\-metadata_name |
| 75 |
Matches any trait on the current object which does not have *metadata_name* |
| 76 |
metadata. |
| 77 |
|
| 78 |
prefix+metadata_name |
| 79 |
Matches any trait on the current object whose name begins with *prefix* and |
| 80 |
which has *metadata_name* metadata. |
| 81 |
|
| 82 |
prefix-metadata_name |
| 83 |
Matches any trait on the current object whose name begins with *prefix* and |
| 84 |
which does not have *metadata_name* metadata. |
| 85 |
|
| 86 |
\+ |
| 87 |
Matches all traits on the current object. |
| 88 |
|
| 89 |
pattern* |
| 90 |
Matches object graphs where *pattern* occurs one or more times (useful for |
| 91 |
setting up listeners on recursive data structures like trees or linked |
| 92 |
lists). |
| 93 |
|
| 94 |
Name Syntax Examples |
| 95 |
-------------------- |
| 96 |
|
| 97 |
Some examples of valid names and their meaning are as follows: |
| 98 |
|
| 99 |
'foo,bar,baz' |
| 100 |
Listen for trait changes to *object.foo*, *object.bar*, and *object.baz*. |
| 101 |
|
| 102 |
['foo','bar','baz'] |
| 103 |
Equivalent to 'foo,bar,baz', but may be more useful in cases where the |
| 104 |
individual items are computed. |
| 105 |
|
| 106 |
'foo.bar.baz' |
| 107 |
Listen for trait changes to *object.foo.bar.baz*. |
| 108 |
|
| 109 |
'foo.[bar,baz]' |
| 110 |
Listen for trait changes to *object.foo.bar* and *object.foo.baz*. |
| 111 |
|
| 112 |
'([left,right]).name' |
| 113 |
Listen for trait changes to the *name* trait of each node of a tree having |
| 114 |
*left* and *right* links to other tree nodes, and where *object* is the |
| 115 |
root node of the tree. |
| 116 |
|
| 117 |
'+dirty' |
| 118 |
Listen for trait changes on any trait in the *object* which has the 'dirty' |
| 119 |
metadata set. |
| 120 |
|
| 121 |
'foo.+dirty' |
| 122 |
Listen for trait changes on any trait in *object.foo* which has the 'dirty' |
| 123 |
metadata set. |
| 124 |
|
| 125 |
'foo.[bar,-dirty]' |
| 126 |
Listen for trait changes on *object.foo.bar* or any trait on *object.foo* |
| 127 |
which does not have 'dirty' metadata set. |
| 128 |
|
| 129 |
Additional Semantic Rules |
| 130 |
------------------------- |
| 131 |
|
| 132 |
Note that any of the intermediate (i.e., non-final) links in a pattern can be |
| 133 |
traits of type **Instance**, **List** or **Dict**. In the case of **List** and |
| 134 |
**Dict** traits, the subsequent portion of the pattern is applied to each item |
| 135 |
in the list, or value in the dictionary. |
| 136 |
|
| 137 |
For example, if *self.children* is a list, 'children.name' listens for trait |
| 138 |
changes to the *name* trait for each item in the *self.children* list. |
| 139 |
|
| 140 |
Also note that items added to or removed from a list or dictionary in the |
| 141 |
pattern will cause the *handler* routine to be invoked as well, since this is |
| 142 |
treated as an *implied* change to the item's trait being monitored. |
| 143 |
|
| 144 |
Notification Handler Signatures |
| 145 |
------------------------------- |
| 146 |
|
| 147 |
The signature of the *handler* supplied also has an effect on how changes to |
| 148 |
intermediate traits are processed. The five valid handler signatures are: |
| 149 |
|
| 150 |
1. handler() |
| 151 |
2. handler(new) |
| 152 |
3. handler(name,new) |
| 153 |
4. handler(object,name,new) |
| 154 |
5. handler(object,name,old,new) |
| 155 |
|
| 156 |
For signatures 1, 4 and 5, any change to any element of a path being listened |
| 157 |
to invokes the handler with information about the particular element that was |
| 158 |
modified (e.g., if the item being monitored is 'foo.bar.baz', a change to |
| 159 |
'bar' will call *handler* with the following information: |
| 160 |
|
| 161 |
object |
| 162 |
object.foo |
| 163 |
name |
| 164 |
bar |
| 165 |
old |
| 166 |
old value for object.foo.bar |
| 167 |
new |
| 168 |
new value for object.foo.bar |
| 169 |
|
| 170 |
If one of the intermediate links is a **List** or **Dict**, the call to |
| 171 |
*handler* may report an *_items* changed event. If in the previous |
| 172 |
example, *bar* is a **List**, and a new item is added to *bar*, then |
| 173 |
the information passed to *handler* would be: |
| 174 |
|
| 175 |
object object.foo name bar_items old **Undefined** new **TraitListEvent** |
| 176 |
whose *added* trait contains the new item added to *bar*. |
| 177 |
|
| 178 |
For signatures 2 and 3, the *handler* does not receive enough information to |
| 179 |
discern between a change to the final trait being listened to and a change to |
| 180 |
an intermediate link. In this case, the event dispatcher will attempt to map a |
| 181 |
change to an intermediate link to its effective change on the final trait. |
| 182 |
This only works if all of the intermediate links are single values (such as an |
| 183 |
**Instance** or **Any** trait) and not **Lists** or **Dicts**. If the modified |
| 184 |
intermediate trait or any subsequent intermediate trait preceding the final |
| 185 |
trait is a **List** or **Dict**, then a **TraitError** is raised, since the |
| 186 |
effective value for the final trait cannot in general be resolved |
| 187 |
unambiguously. |
| 188 |
|
| 189 |
Handler signature 1 also has the special characteristic that if a final trait |
| 190 |
is a **List** or **Dict**, it will automatically handle *_items* changed |
| 191 |
events for the final trait as well. This can be useful in cases where the |
| 192 |
*handler* only needs to know that some aspect of the final trait has been |
| 193 |
changed. For all other *handler* signatures, you must explicitly specify the |
| 194 |
*xxx_items* trait if you want to be notified of changes to any of the items of |
| 195 |
the *xxx* trait. |
| 196 |
|
| 197 |
Backward Compatibility |
| 198 |
---------------------- |
| 199 |
|
| 200 |
The new extended trait name support in Traits 3.0 has one slight semantic |
| 201 |
difference with the pre-Traits 3.0 *on_trait_change* method. |
| 202 |
|
| 203 |
Prior to Traits 3.0, it was necessary to make two separate calls to |
| 204 |
*on_trait_change* in order to set up listeners on a **List** or **Dict** |
| 205 |
trait's value and the contents of its value, as shown in the following |
| 206 |
example:: |
| 207 |
|
| 208 |
class Department(HasTraits): |
| 209 |
|
| 210 |
employees = List(Employee) |
| 211 |
|
| 212 |
... |
| 213 |
|
| 214 |
a_department.on_trait_change(some_listener, 'employees') |
| 215 |
a_department.on_trait_change(some_listener_items, 'employees_items') |
| 216 |
|
| 217 |
In Traits 3.0, this is still the case if the *some_listener* function has one |
| 218 |
or more arguments. However, if it has no arguments, the *on_trait_change* |
| 219 |
method will automatically call the function either when the trait's value or |
| 220 |
its value's contents change. So in Traits 3.0 it is only necessary to write:: |
| 221 |
|
| 222 |
a_department.on_trait_change(some_listener, 'employees') |
| 223 |
|
| 224 |
if the *some_listener* (and *some_listener_items*) function has no arguments. |
| 225 |
|
| 226 |
The net effect of this difference is that code written prior to Traits 3.0 |
| 227 |
could set up two listeners (e.g. *some_listener* and *some_listener_items*, as |
| 228 |
in the example), and then have *both* methods called when the contents of the |
| 229 |
trait are modified if the *some_listener* method takes no arguments. Since no |
| 230 |
data is passed to the *some_listener* function, there is probably no harm in |
| 231 |
doing this, but it does create unnecessary notification handler calls. |
| 232 |
|
| 233 |
As a result, to avoid creating this unwanted overhead in existing code, the |
| 234 |
*on_trait_change* method applies pre-Traits 3.0 semantics to all simple names |
| 235 |
passed to it (e.g. 'employees'). If you are writing new code and want to |
| 236 |
take advantage of the new Traits 3.0 *on_trait_change* semantics for a simple |
| 237 |
trait name, you will need to modify the name to use some recognizable aspect of |
| 238 |
the new extended trait name syntax. |
| 239 |
|
| 240 |
For example, either of the following lines would cause *new style* semantics to |
| 241 |
be applied to the *employees* trait:: |
| 242 |
|
| 243 |
a_department.on_trait_change(some_listener, ' employees') |
| 244 |
|
| 245 |
a_department.on_trait_change(some_listener, '[employees]') |
| 246 |
|
| 247 |
A Complete Example |
| 248 |
------------------ |
| 249 |
|
| 250 |
Refer to the code tabs of this lesson for a complete example using |
| 251 |
*on_trait_change* with an extended trait name. In particular, check near the |
| 252 |
bottom of the **Example** tab for the code that sets up an extended trait |
| 253 |
change notification handler using *on_trait_change*. |
| 254 |
""" |
| 255 |
|
| 256 |
from traits.api import HasTraits, Int, List, Str |
| 257 |
|
| 258 |
|
| 259 |
# --[Employee Class]----------------------------------------------------------- |
| 260 |
class Employee(HasTraits): |
| 261 |
|
| 262 |
# The name of the employee: |
| 263 |
name = Str |
| 264 |
|
| 265 |
# The number of sick days they have taken this year: |
| 266 |
sick_days = Int |
| 267 |
|
| 268 |
|
| 269 |
# --[Department Class]--------------------------------------------------------- |
| 270 |
class Department(HasTraits): |
| 271 |
|
| 272 |
# The name of the department: |
| 273 |
name = Str |
| 274 |
|
| 275 |
# The employees in the department: |
| 276 |
employees = List(Employee) |
| 277 |
|
| 278 |
|
| 279 |
# --[Corporation Class]-------------------------------------------------------- |
| 280 |
class Corporation(HasTraits): |
| 281 |
|
| 282 |
# The name of the corporation: |
| 283 |
name = Str |
| 284 |
|
| 285 |
# The departments within the corporation: |
| 286 |
departments = List(Department) |
| 287 |
|
| 288 |
|
| 289 |
# --[Example*]----------------------------------------------------------------- |
| 290 |
# Create some sample employees: |
| 291 |
millie = Employee(name="Millie", sick_days=2) |
| 292 |
ralph = Employee(name="Ralph", sick_days=3) |
| 293 |
tom = Employee(name="Tom", sick_days=1) |
| 294 |
slick = Employee(name="Slick", sick_days=16) |
| 295 |
marcelle = Employee(name="Marcelle", sick_days=7) |
| 296 |
reggie = Employee(name="Reggie", sick_days=11) |
| 297 |
dave = Employee(name="Dave", sick_days=0) |
| 298 |
bob = Employee(name="Bob", sick_days=1) |
| 299 |
alphonse = Employee(name="Alphonse", sick_days=5) |
| 300 |
|
| 301 |
# Create some sample departments: |
| 302 |
accounting = Department(name="accounting", employees=[millie, ralph, tom]) |
| 303 |
|
| 304 |
sales = Department(name="Sales", employees=[slick, marcelle, reggie]) |
| 305 |
|
| 306 |
development = Department(name="Development", employees=[dave, bob, alphonse]) |
| 307 |
|
| 308 |
# Create a sample corporation: |
| 309 |
acme = Corporation( |
| 310 |
name="Acme, Inc.", departments=[accounting, sales, development] |
| 311 |
) |
| 312 |
|
| 313 |
|
| 314 |
# Define a corporate 'whistle blower' function: |
| 315 |
def sick_again(object, name, old, new): |
| 316 |
print( |
| 317 |
"%s just took sick day number %d for this year!" % (object.name, new) |
| 318 |
) |
| 319 |
|
| 320 |
|
| 321 |
# Set up the function as a listener: |
| 322 |
acme.on_trait_change(sick_again, "departments.employees.sick_days") |
| 323 |
|
| 324 |
# Now let's try it out: |
| 325 |
slick.sick_days += 1 |
| 326 |
reggie.sick_days += 1 |