| 1 |
.. _observe-notification: |
| 2 |
|
| 3 |
Trait Notification |
| 4 |
================== |
| 5 |
|
| 6 |
When the value of an attribute changes, other parts of the program might need |
| 7 |
to be notified that the change has occurred. The Traits package makes this |
| 8 |
possible for trait attributes. This functionality lets you write programs |
| 9 |
using the same, powerful event-driven model that is used in writing user |
| 10 |
interfaces and for other problem domains. |
| 11 |
|
| 12 |
Traits 6.1 introduces a new API for configuring traits notifications: |
| 13 |
**observe**, which is intended to fully replace an older API |
| 14 |
(**on_trait_change**) in order to overcome some of its limitations and flaws. |
| 15 |
While **on_trait_change** is still supported, it may be removed in the future. |
| 16 |
See :ref:`on-trait-change-notification` for details on this older API. |
| 17 |
|
| 18 |
Requesting trait attribute change notifications can be done in these |
| 19 |
ways: |
| 20 |
|
| 21 |
* Via class definition: By decorating methods on the class with the |@observe| |
| 22 |
decorator to indicate that they handle notification for specified attributes. |
| 23 |
* Via instance method: By calling |HasTraits.observe| instance method to establish (or remove) change |
| 24 |
notification handlers. |
| 25 |
|
| 26 |
Via class definition |
| 27 |
-------------------- |
| 28 |
|
| 29 |
Observers can be defined for every instance of a |HasTraits| subclass by |
| 30 |
applying the |@observe| decorator on an instance method. For example, to |
| 31 |
observe changes to a specific trait on an object: |
| 32 |
|
| 33 |
.. literalinclude:: /../../examples/tutorials/doc_examples/examples/observe_decorator.py |
| 34 |
:start-at: from traits.api |
| 35 |
|
| 36 |
The decorated function *notify_age_change* is called a **change handler**. |
| 37 |
Section :ref:`observe-handler` explains the signature and behaviour expected |
| 38 |
for these functions. The value *"age"* is called an **expression**. Section |
| 39 |
:ref:`observe-expression` explains how to write an expression for |
| 40 |
observing traits and containers following different patterns. |
| 41 |
|
| 42 |
Notice that a change event is emitted at instance construction time because the |
| 43 |
initial value is different from the default value. The *post_init* argument can |
| 44 |
be used to delay adding the change handler until after the object state is set. |
| 45 |
|
| 46 |
.. literalinclude:: /../../examples/tutorials/doc_examples/examples/observe_post_init.py |
| 47 |
:start-at: @observe |
| 48 |
:lines: 1-3 |
| 49 |
|
| 50 |
Via instance method |
| 51 |
------------------- |
| 52 |
|
| 53 |
The |HasTraits.observe| method on |HasTraits| is useful for adding or removing |
| 54 |
change handlers on a per instance basis. The example above can be rewritten like |
| 55 |
this: |
| 56 |
|
| 57 |
.. literalinclude:: /../../examples/tutorials/doc_examples/examples/observe_method.py |
| 58 |
:start-at: from traits.api |
| 59 |
|
| 60 |
The behaviors of the |@observe| decorator and the |HasTraits.observe| instance |
| 61 |
are very similar. The only differences are: |
| 62 |
|
| 63 |
* |@observe| decorator does not support removing change handlers. |
| 64 |
* |@observe| decorator supports setting up change handlers prior to setting |
| 65 |
object state at instantiation. |
| 66 |
* |@observe| decorator sets up change handlers for all instances of a class |
| 67 |
and those change handlers can be inherited by subclasses. |
| 68 |
|
| 69 |
Unless otherwise stated, the following sections apply to both methods for |
| 70 |
setting up change notifications. |
| 71 |
|
| 72 |
.. _observe-expression: |
| 73 |
|
| 74 |
The *expression* Parameter |
| 75 |
-------------------------- |
| 76 |
The *expression* parameter in |@observe| provides significant flexibility |
| 77 |
in specifying not just attributes directly on the current object, but also |
| 78 |
attributes on nested objects and containers. |
| 79 |
|
| 80 |
There are two approaches for creating an expression: |
| 81 |
|
| 82 |
* :ref:`observe-mini-language` |
| 83 |
* :ref:`observe-expression-object` |
| 84 |
|
| 85 |
.. _observe-mini-language: |
| 86 |
|
| 87 |
Traits Mini Language |
| 88 |
```````````````````` |
| 89 |
Traits Mini Language is a domain specific language which provides a convenient |
| 90 |
and concise way to specify observation rules via a single text. It supports |
| 91 |
most of the use cases commonly encountered by users. |
| 92 |
|
| 93 |
.. rubric:: Semantics of Traits DSL |
| 94 |
|
| 95 |
.. list-table:: |
| 96 |
:widths: 15 25 |
| 97 |
:header-rows: 1 |
| 98 |
|
| 99 |
* - Pattern |
| 100 |
- Meaning |
| 101 |
* - *attr1\.attr2* |
| 102 |
- Matches a trait named *attr2* on an object referenced by a trait named |
| 103 |
*attr1* on the current object. Changes to *attr1* or *attr2* will |
| 104 |
trigger notifications. |
| 105 |
* - *attr1\:attr2* |
| 106 |
- Matches a trait named *attr2* on an object referenced by a trait named |
| 107 |
*attr1* on the current object. Changes to *attr2* will trigger |
| 108 |
notifications. Changes to *attr1* will not. |
| 109 |
* - *attr1\, attr2* |
| 110 |
- Matches trait named *attr1* or trait named *attr2*. |
| 111 |
* - *items* |
| 112 |
- Matching items in a list or dict or set, or a trait named "items". |
| 113 |
* - [*item1*, *item2*, ..., *itemN*] |
| 114 |
- Matches any of the specified expressions. |
| 115 |
* - *\** |
| 116 |
- Matches any trait. The ``"*"`` may only appear as a "terminal" item in |
| 117 |
an expression - one that's not followed directly or indirectly by a |
| 118 |
``"."`` or ``":"`` connector. For example, ``"*"``, ``"name.*"`` and |
| 119 |
``"[a.*, b.c]"`` are all permitted, but ``"*.name"`` and ``[a, *].name`` |
| 120 |
are not. |
| 121 |
* - *+metadata_name* |
| 122 |
- Matches any trait on the object that has metadata *metadata_name* |
| 123 |
|
| 124 |
.. rubric:: Examples of Traits DSL |
| 125 |
|
| 126 |
.. list-table:: |
| 127 |
:widths: 15 25 |
| 128 |
:header-rows: 1 |
| 129 |
|
| 130 |
* - Example |
| 131 |
- Meaning |
| 132 |
* - ``"*"`` |
| 133 |
- Matches all traits on the current object. A change to any trait will |
| 134 |
trigger notifications. |
| 135 |
* - ``"foo.+updated"`` |
| 136 |
- Matches any trait on the *foo* that has a metadata attribute named |
| 137 |
*updated*. Changes on those traits and changes on *foo* will trigger |
| 138 |
notifications. |
| 139 |
* - ``"foo,bar"`` |
| 140 |
- Matches traits named *foo* or *bar* on the current object. Changes on |
| 141 |
*foo* or *bar* will trigger notifications. |
| 142 |
* - ``"foo:[bar,baz]"`` |
| 143 |
- Matches *foo.bar* or *foo.baz* on the current object. Changes on |
| 144 |
*foo.bar* or *foo.baz* will trigger notifications, but changes on *foo* |
| 145 |
will not trigger notifications. |
| 146 |
* - ``"container.items.value"`` |
| 147 |
- If *container* is a list or dict or set, matches the *value* trait on an |
| 148 |
object that is an item of the container. If *container* is an instance |
| 149 |
of *HasTraits*, matches attribute *container.items.value* on the current |
| 150 |
object. Changes to any of these will trigger notifications. |
| 151 |
* - ``"container:items:value"`` |
| 152 |
- If *container* is a list or dict or set, matches the *value* trait on an |
| 153 |
object that is an item of the container. If *container* is an instance |
| 154 |
of *HasTraits*, matches attribute *container.items.value* on the current |
| 155 |
object. Only changes to *value* will trigger notifications, assignments |
| 156 |
or mutations on *container* will not trigger notifications. |
| 157 |
* - ``"container:items:*"`` |
| 158 |
- If *container* is a list or dict or set, matches all traits on an object |
| 159 |
that is an item of the container. |
| 160 |
|
| 161 |
.. _observe-expression-object: |
| 162 |
|
| 163 |
Expressions as objects |
| 164 |
`````````````````````` |
| 165 |
|
| 166 |
|ObserverExpression| supports all the use cases supported by the Traits Mini Language |
| 167 |
and beyond. Users can compose these objects programmatically and supply |
| 168 |
them to |@observe|. These objects are typically constructed using the following |
| 169 |
functions from the |observation.api| module. |
| 170 |
|
| 171 |
.. list-table:: |
| 172 |
:widths: 15 25 |
| 173 |
:header-rows: 1 |
| 174 |
|
| 175 |
* - Function |
| 176 |
- Purpose |
| 177 |
* - |trait| |
| 178 |
- For observing a specific named trait. |
| 179 |
* - |metadata| |
| 180 |
- For observing multiple traits with specific metadata. |
| 181 |
* - |dict_items| |
| 182 |
- For observing items in a dict. |
| 183 |
* - |list_items| |
| 184 |
- For observing items in a list. |
| 185 |
* - |set_items| |
| 186 |
- For observing items in a set. |
| 187 |
* - |match| |
| 188 |
- For observing traits satisfying a user-defined filter. |
| 189 |
* - |anytrait| |
| 190 |
- For observing all traits on an object. |
| 191 |
* - |parse| |
| 192 |
- For parsing a string written in Traits domain specific language into an |
| 193 |
expression object. |
| 194 |
|
| 195 |
Users can combine complex expressions using |ObserverExpression.then| or |
| 196 |
Python's bitwise-or (`|`) operation. |
| 197 |
|
| 198 |
Most of these functions will have a **notify** argument for setting whether |
| 199 |
notifications should be fired for changes. |
| 200 |
|
| 201 |
.. rubric:: Example expressions |
| 202 |
|
| 203 |
* ``trait("attr1")`` |
| 204 |
Matches a trait named *attr1* on an object and notifies for changes. |
| 205 |
|
| 206 |
* ``trait("attr1", optional=True)`` |
| 207 |
Matches a trait named *attr1* if it is defined. Ignore if it is not defined. |
| 208 |
|
| 209 |
* ``trait("attr1", notify=False).trait("attr2")`` |
| 210 |
Matches a trait named *attr2* on an object referenced by a trait named |
| 211 |
*attr1* on the current object. Changes to *attr2* will trigger |
| 212 |
notifications, while changes to *attr1* do not. |
| 213 |
|
| 214 |
* ``trait("foo").list_items().list_items().trait("value")`` |
| 215 |
Matches the *value* trait on an item of a nested list in another list |
| 216 |
*foo*. Assignment changes to *foo*, mutations to the lists or changes |
| 217 |
to *value* will trigger notifications. |
| 218 |
|
| 219 |
* ``metadata("updated")`` |
| 220 |
Matches any trait on the current that has a metadata attribute named |
| 221 |
*updated*. Changes on those traits will trigger notifications. |
| 222 |
|
| 223 |
* ``trait("foo") | trait("bar")`` |
| 224 |
Matches traits named *foo* or *bar* on the current object. Changes on |
| 225 |
*foo* or *bar* will trigger notifications. |
| 226 |
|
| 227 |
* ``trait("foo").then(trait("bar") | trait("baz"))`` |
| 228 |
Matches *foo.bar* or *foo.baz* on the current object. Changes on *foo*, |
| 229 |
*foo.bar* or *foo.baz* will trigger notifications. |
| 230 |
|
| 231 |
* ``anytrait()`` |
| 232 |
Matches all traits on the current object. |
| 233 |
|
| 234 |
* ``trait("foo").anytrait()`` |
| 235 |
Matches all traits on *foo* on the current object. Changes on *foo* or |
| 236 |
the nested attributes will trigger notifications. |
| 237 |
|
| 238 |
* ``trait("foo", notify=False).anytrait()`` |
| 239 |
Matches all traits on *foo* on the current object. Changes on the nested |
| 240 |
attributes will trigger notifications. Changes on *foo* will not trigger |
| 241 |
notifications. |
| 242 |
|
| 243 |
|
| 244 |
.. rubric:: Extend an expression in text |
| 245 |
|
| 246 |
Using the |parse| function, one can extend an expression in text |
| 247 |
with additional features supported by |ObserverExpression|. For example:: |
| 248 |
|
| 249 |
parse("foo.bar").match(lambda name, trait: name.startswith("my_")) |
| 250 |
|
| 251 |
will observe traits with a prefix "my\_" on *foo.bar* on the current object. |
| 252 |
|
| 253 |
|
| 254 |
.. _observe-handler: |
| 255 |
|
| 256 |
Notification Handler |
| 257 |
-------------------- |
| 258 |
|
| 259 |
By default, the **handler** is invoked immediately after the change has |
| 260 |
occurred. The **dispatch** parameter in |@observe| can be set such that the |
| 261 |
handler is dispatched elsewhere to be invoked later (e.g. on a GUI event loop). |
| 262 |
|
| 263 |
The following expectations apply to any change handler: |
| 264 |
|
| 265 |
* It must accept one argument: the **event** parameter (see below) |
| 266 |
* It is called **after** a change has occurred |
| 267 |
* No assumptions should be made about the order of which handlers are called |
| 268 |
for a given change event. A change event can have many change handlers. |
| 269 |
* No exceptions should be raised from a change handler. Any unexpected |
| 270 |
exceptions will be captured and logged. |
| 271 |
|
| 272 |
When the handler is invoked, it is given an **event** object which provides |
| 273 |
information about the change observed. The type and signature of *event* |
| 274 |
depend on the context of the change. However they all include a parameter |
| 275 |
*object* referring to the object being modified: |
| 276 |
|
| 277 |
.. rubric:: Change event types |
| 278 |
|
| 279 |
.. list-table:: |
| 280 |
:widths: 15 25 |
| 281 |
:header-rows: 1 |
| 282 |
|
| 283 |
* - Change |
| 284 |
- Event Object Type |
| 285 |
* - Attribute value |
| 286 |
- |TraitChangeEvent| |
| 287 |
* - Dict membership |
| 288 |
- |DictChangeEvent| |
| 289 |
* - List membership |
| 290 |
- |ListChangeEvent| |
| 291 |
* - Set membership |
| 292 |
- |SetChangeEvent| |
| 293 |
|
| 294 |
|
| 295 |
This means if the handler needs to act on the specific details of the change |
| 296 |
event, |@observe| should be configured to only notify for that specific type of |
| 297 |
changes, or the handler will need to check the type of the event parameter when |
| 298 |
it is invoked. The following example shows the first option: |
| 299 |
|
| 300 |
.. literalinclude:: /../../examples/tutorials/doc_examples/examples/observe_different_events.py |
| 301 |
:start-at: from traits.api |
| 302 |
|
| 303 |
|
| 304 |
Features and fixes provided by |@observe| |
| 305 |
----------------------------------------- |
| 306 |
|
| 307 |
In addition to the new flexibility provided by the |ObserverExpression| |
| 308 |
object, |@observe| aims at overcoming a number of design flaws and |
| 309 |
limitations in the older API. The following sections highlight the differences |
| 310 |
and new features supported by |@observe|. |
| 311 |
|
| 312 |
Existence of observed items is checked by default |
| 313 |
````````````````````````````````````````````````` |
| 314 |
|
| 315 |
The existence of a trait is checked when the handler is being added to the |
| 316 |
instance:: |
| 317 |
|
| 318 |
class Foo(HasTraits): |
| 319 |
name = Str() |
| 320 |
|
| 321 |
@observe("nam") # typo, or an omission in renaming |
| 322 |
def _name_updated(self, event): |
| 323 |
print("name changed") |
| 324 |
|
| 325 |
foo = Foo() # Error here: Trait named 'nam' not found |
| 326 |
|
| 327 |
There are situations where it is desirable to add the change handler before |
| 328 |
a trait is defined. |
| 329 |
|
| 330 |
In that case, the *optional* argument on |trait| can be used: |
| 331 |
|
| 332 |
.. literalinclude:: /../../examples/tutorials/doc_examples/examples/observe_optional.py |
| 333 |
:start-at: class |
| 334 |
|
| 335 |
|
| 336 |
Arbitrarily nested containers are supported |
| 337 |
``````````````````````````````````````````` |
| 338 |
|
| 339 |
It is now possible to notify for changes on an object in a very nested |
| 340 |
container. Suppose we have these classes:: |
| 341 |
|
| 342 |
class Bar(HasTraits): |
| 343 |
value = Int() |
| 344 |
|
| 345 |
class Foo(HasTraits): |
| 346 |
bars = Dict(Str(), List(Instance(Bar))) |
| 347 |
|
| 348 |
To observe *Bar.value*, one can do:: |
| 349 |
|
| 350 |
foo = Foo() |
| 351 |
foo.observe(handler, "bars.items.items.value") |
| 352 |
|
| 353 |
Or:: |
| 354 |
|
| 355 |
foo.observe(handler, trait("bars").dict_items().list_items().trait("value") |
| 356 |
|
| 357 |
|
| 358 |
|@observe| decorator can be stacked |
| 359 |
``````````````````````````````````` |
| 360 |
|
| 361 |
The same handler can be used against different changes and with different |
| 362 |
parameters. With |@observe|, one can stack the decorator on the same method:: |
| 363 |
|
| 364 |
@observe("attr1", post_init=True) |
| 365 |
@observe("attr2", post_init=False) |
| 366 |
def _update_plots(self, event): |
| 367 |
... |
| 368 |
|
| 369 |
|
| 370 |
Duplicated objects are now monitored |
| 371 |
```````````````````````````````````` |
| 372 |
|
| 373 |
Consider this example:: |
| 374 |
|
| 375 |
class Apple(HasTraits): |
| 376 |
count = Int(0) |
| 377 |
|
| 378 |
class Bowl(HasTraits): |
| 379 |
apples = List(Instance(Apple)) |
| 380 |
|
| 381 |
@observe('apples:items:count') |
| 382 |
def print_status(self, event): |
| 383 |
print("Count changed to {event.new}".format(event)) |
| 384 |
|
| 385 |
granny_smith = Apple() |
| 386 |
bowl = Bowl(apples=[granny_smith, granny_smith]) |
| 387 |
granny_smith.count += 1 # print: 'Count changed to 1' |
| 388 |
|
| 389 |
The **granny_smith** object is repeated in the **apples** list. When one of the |
| 390 |
items is removed from the list, the **granny_smith** object is still there and |
| 391 |
we expect a change notification:: |
| 392 |
|
| 393 |
bowl.apples.pop() # granny_smith is still in the list. |
| 394 |
granny_smith.count += 1 # print: 'Count changed to 2' |
| 395 |
|
| 396 |
In the older API, this situation was not accounted for. With |@observe|, this |
| 397 |
situation is handled by keeping a reference count on the observed objects. |
| 398 |
|
| 399 |
This means |HasTraits.observe| cannot be idempotent. |
| 400 |
|
| 401 |
|
| 402 |
|HasTraits.observe| is not idempotent |
| 403 |
````````````````````````````````````` |
| 404 |
|
| 405 |
For most use cases, change handlers can be put up in a fire-and-forget |
| 406 |
fashion and they are never removed. However for some use cases, it is important |
| 407 |
to remove change handlers when they are no longer needed. |
| 408 |
|
| 409 |
Calling |HasTraits.observe| to add an existing change handler will increment |
| 410 |
an internal reference count. The change handler can only be completely removed |
| 411 |
by calling |HasTraits.observe| the same number of times with *remove* set to |
| 412 |
True. |
| 413 |
|
| 414 |
In other words:: |
| 415 |
|
| 416 |
foo.observe(handler, "number") |
| 417 |
foo.observe(handler, "number") |
| 418 |
foo.observe(handler, "number") |
| 419 |
|
| 420 |
foo.number += 1 # handler is called once |
| 421 |
|
| 422 |
foo.observe(handler, "number", remove=True) |
| 423 |
foo.observe(handler, "number", remove=True) |
| 424 |
|
| 425 |
foo.number += 1 # handler is still called once |
| 426 |
|
| 427 |
foo.observe(handler, "number", remove=True) |
| 428 |
|
| 429 |
foo.number += 1 # handler is not called. |
| 430 |
|
| 431 |
Attempts to remove change handlers that do not exist will lead to a |
| 432 |
|NotifierNotFound| exception. |
| 433 |
|
| 434 |
|
| 435 |
Migration from |@on_trait_change| |
| 436 |
--------------------------------- |
| 437 |
|
| 438 |
|@observe| can be used alongside |@on_trait_change|. Therefore it is possible |
| 439 |
for projects to add new code using |@observe| while slowly migrating existing |
| 440 |
code from |@on_trait_change| to |@observe|. |
| 441 |
|
| 442 |
The following sections provide some guide to help migrations. |
| 443 |
|
| 444 |
Observe extended trait names |
| 445 |
```````````````````````````` |
| 446 |
|
| 447 |
The expression syntax has not changed for extended trait names excluding |
| 448 |
containers. |
| 449 |
|
| 450 |
For example, given these classes:: |
| 451 |
|
| 452 |
class Bar(HasTraits): |
| 453 |
value = Int() |
| 454 |
|
| 455 |
class Foo(HasTraits): |
| 456 |
bar = Instance(Bar) |
| 457 |
|
| 458 |
To observe *bar.value* on an instance of *Foo*, this:: |
| 459 |
|
| 460 |
@on_trait_change("bar.value") |
| 461 |
|
| 462 |
will be changed to this:: |
| 463 |
|
| 464 |
@observe("bar.value") |
| 465 |
|
| 466 |
|
| 467 |
Observe nested attributes in a container |
| 468 |
```````````````````````````````````````` |
| 469 |
|
| 470 |
Suppose we have these classes:: |
| 471 |
|
| 472 |
class Bar(HasTraits): |
| 473 |
value = Int() |
| 474 |
|
| 475 |
class Foo(HasTraits): |
| 476 |
container = List(Instance(Bar)) |
| 477 |
|
| 478 |
To notify for changes on *Bar.value* for an item in *Foo.container*, |
| 479 |
with |@on_trait_change|, one may do:: |
| 480 |
|
| 481 |
@on_trait_change("container.value") |
| 482 |
|
| 483 |
Where the container nature is deduced at runtime (see |
| 484 |
:ref:`trait-items-handlers`). |
| 485 |
|
| 486 |
With |@observe|, one will explicitly specify when items of a container are |
| 487 |
being observed, like this:: |
| 488 |
|
| 489 |
@observe("container.items.value") |
| 490 |
|
| 491 |
or:: |
| 492 |
|
| 493 |
@observe(trait("container").list_items().trait("value")) |
| 494 |
|
| 495 |
Similarly, this:: |
| 496 |
|
| 497 |
@on_trait_change("container_items.value") |
| 498 |
|
| 499 |
will be changed to this:: |
| 500 |
|
| 501 |
@observe("container:items.value") |
| 502 |
|
| 503 |
or this:: |
| 504 |
|
| 505 |
@observe(trait("container", notify=False).list_items().trait("value")) |
| 506 |
|
| 507 |
The specially named *name*\_items for listening to container changes is still |
| 508 |
defined for supporting |@on_trait_change|. Monitoring this *name*\_items trait |
| 509 |
with |@observe| is discouraged as this special trait may be removed when |
| 510 |
|@on_trait_change| is removed. |
| 511 |
|
| 512 |
|
| 513 |
Change handler signature is different |
| 514 |
````````````````````````````````````` |
| 515 |
|
| 516 |
|@on_trait_change| supports a range of call |
| 517 |
:ref:`signatures <notification-handler-signatures>` for the change handler. |
| 518 |
|@observe| supports only one. The single argument contains different content |
| 519 |
based on the type of changes being handled (see |
| 520 |
:ref:`observe-handler`). |
| 521 |
|
| 522 |
For example, for this handler:: |
| 523 |
|
| 524 |
name = Str() |
| 525 |
|
| 526 |
@on_trait_change("name") |
| 527 |
def name_updated(self, object, name, old, new): |
| 528 |
print(object, name, old, new) |
| 529 |
|
| 530 |
It will have to be changed to:: |
| 531 |
|
| 532 |
@observe("name") |
| 533 |
def name_updated(self, event): |
| 534 |
print(event.object, event.name, event.old, event.new) |
| 535 |
|
| 536 |
|
| 537 |
For mutations to container, e.g.:: |
| 538 |
|
| 539 |
container = List() |
| 540 |
|
| 541 |
@on_trait_change("container_items") |
| 542 |
def name_updated(self, object, name, old, new): |
| 543 |
print("Index: {new.index}") |
| 544 |
print("Added: {new.added}") |
| 545 |
print("Removed: {new.removed}") |
| 546 |
|
| 547 |
It will have to be changed to:: |
| 548 |
|
| 549 |
container = List(comparison_mode=ComparisonMode.identity) |
| 550 |
|
| 551 |
@observe("container:items") |
| 552 |
def name_updated(self, event): |
| 553 |
print("Index: {event.index}") |
| 554 |
print("Added: {event.added}") |
| 555 |
print("Removed: {event.removed}") |
| 556 |
|
| 557 |
|
| 558 |
Syntax "[]" is not supported |
| 559 |
```````````````````````````` |
| 560 |
|
| 561 |
Suppose we have this class:: |
| 562 |
|
| 563 |
class Foo(HasTraits): |
| 564 |
container = List(Instance(Bar)) |
| 565 |
|
| 566 |
To notify for both reassignment of *Foo.container* and mutation on the list, |
| 567 |
one may do:: |
| 568 |
|
| 569 |
@on_trait_change("container[]") |
| 570 |
|
| 571 |
or:: |
| 572 |
|
| 573 |
@on_trait_change(["container", "container_items"]) |
| 574 |
|
| 575 |
With |@observe|, the syntax will be changed to:: |
| 576 |
|
| 577 |
@observe("container.items") |
| 578 |
|
| 579 |
or:: |
| 580 |
|
| 581 |
@observe(trait("container").list_items()) |
| 582 |
|
| 583 |
Note that assignment changes to *container* and mutations to the container will |
| 584 |
emit different event types for the change handler. See |
| 585 |
:ref:`observe-handler` for details. |
| 586 |
|
| 587 |
|
| 588 |
Syntax "-" is not supported |
| 589 |
``````````````````````````` |
| 590 |
|
| 591 |
With |@on_trait_change|, the syntax *"-metadata_name"* is used to notify |
| 592 |
for changes on traits that do NOT have a metadata attribute with the given |
| 593 |
name. This usage can be replaced by |match|:: |
| 594 |
|
| 595 |
match(lambda name, trait: trait.metadata_name is None) |
| 596 |
|
| 597 |
|
| 598 |
Dispatch parameter differentiates observers |
| 599 |
``````````````````````````````````````````` |
| 600 |
|
| 601 |
In the following example with |@on_trait_change|, the second call is an no-op |
| 602 |
because a handler for *"name"* has already been added:: |
| 603 |
|
| 604 |
instance.on_trait_change(handler, "name", dispatch="same") |
| 605 |
instance.on_trait_change(handler, "name", dispatch="ui") # does nothing |
| 606 |
|
| 607 |
With |@observe|, the **dispatch** parameter is taken into account for |
| 608 |
distinguishing observers. The following example will result in the change |
| 609 |
handler being called twice, via different dispatching routes:: |
| 610 |
|
| 611 |
instance.observe(handler, "name", dispatch="same") |
| 612 |
instance.observe(handler, "name", dispatch="ui") |
| 613 |
|
| 614 |
Likewise, when removing change handlers, **dispatch** must match the value |
| 615 |
used for putting up the observer:: |
| 616 |
|
| 617 |
instance.observe(handler, "name", dispatch="ui") |
| 618 |
instance.observe(handler, "name", dispatch="ui", remove=True) |
| 619 |
|
| 620 |
.. |
| 621 |
# substitutions |
| 622 |
|
| 623 |
.. |ObserverExpression| replace:: :class:`~traits.observation.expression.ObserverExpression` |
| 624 |
.. |observation.api| replace:: :mod:`~traits.observation.api` |
| 625 |
.. |trait| replace:: :func:`~traits.observation.expression.trait` |
| 626 |
.. |metadata| replace:: :func:`~traits.observation.expression.metadata` |
| 627 |
.. |dict_items| replace:: :func:`~traits.observation.expression.dict_items` |
| 628 |
.. |list_items| replace:: :func:`~traits.observation.expression.list_items` |
| 629 |
.. |set_items| replace:: :func:`~traits.observation.expression.set_items` |
| 630 |
.. |match| replace:: :func:`~traits.observation.expression.match` |
| 631 |
.. |anytrait| replace:: :func:`~traits.observation.expression.anytrait` |
| 632 |
.. |parse| replace:: :func:`~traits.observation.parsing.parse` |
| 633 |
.. |print| replace:: :func:`~traits.observation.expression.print` |
| 634 |
.. |ObserverExpression.then| replace:: :func:`~traits.observation.expression.ObserverExpression.then` |
| 635 |
.. |NotifierNotFound| replace:: :exc:`~traits.observation.exceptions.NotifierNotFound` |
| 636 |
|
| 637 |
.. |TraitChangeEvent| replace:: :class:`~traits.observation.events.TraitChangeEvent` |
| 638 |
.. |ListChangeEvent| replace:: :class:`~traits.observation.events.ListChangeEvent` |
| 639 |
.. |DictChangeEvent| replace:: :class:`~traits.observation.events.DictChangeEvent` |
| 640 |
.. |SetChangeEvent| replace:: :class:`~traits.observation.events.SetChangeEvent` |
| 641 |
|
| 642 |
.. |HasTraits| replace:: :class:`~traits.has_traits.HasTraits` |
| 643 |
.. |@observe| replace:: :func:`~traits.has_traits.observe` |
| 644 |
.. |HasTraits.observe| replace:: :func:`~traits.has_traits.HasTraits.observe` |
| 645 |
|
| 646 |
.. |@on_trait_change| replace:: :func:`~traits.has_traits.on_trait_change` |
| 647 |
.. |HasTraits.on_trait_change| replace:: :func:`~traits.has_traits.HasTraits.on_trait_change` |