File: observe_hints.py

package info (click to toggle)
python-atom 0.12.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,616 kB
  • sloc: cpp: 9,040; python: 6,249; makefile: 123
file content (56 lines) | stat: -rw-r--r-- 1,527 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# --------------------------------------------------------------------------------------
# Copyright (c) 2022-2024, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# --------------------------------------------------------------------------------------
"""Demonstration of the use of static and dynamic observers."""

from typing import Optional

from atom.api import Atom, ChangeDict, observe


class Dog(Atom):
    name: str


class Person(Atom):
    """A simple class representing a person object."""

    name: str

    age: int

    dog: Optional[Dog]

    def _observe_age(self, change: ChangeDict) -> None:
        print("Age changed: {0}".format(change["value"]))

    @observe("name")
    def any_name_i_want(self, change: ChangeDict) -> None:
        print("Name changed: {0}".format(change["value"]))

    @observe("dog.name")
    def another_random_name(self, change: ChangeDict) -> None:
        print("Dog name changed: {0}".format(change["value"]))


def main() -> None:
    bob = Person(name="Robert Paulson", age=40)
    bob.name = "Bobby Paulson"
    bob.age = 50
    bob.dog = Dog(name="Scruffy")

    def watcher_func(change: ChangeDict) -> None:
        print("Watcher func change: {0}".format(change["value"]))

    bob.observe("age", watcher_func)
    bob.age = 51
    bob.unobserve("age", watcher_func)
    bob.age = 52  # No call to watcher func


if __name__ == "__main__":
    main()