Skip to content

ValueSource

Usage

Data sources are abstractions that allow you to define the data being managed by your application independent of the GUI representation of that data. For details on the use of data sources, see the topic guide.

ValueSource is an wrapper around a single atomic value.

from toga.sources import ValueSource

source = ValueSource(42)

# Get the value managed by the source
print(f"Meaning of life, the universe, and everything is {source.value}")

Custom ValueSources

A custom ValueSource has 3 requirements:

  • It must have an accessor attribute that describes the name of the attribute that stores the data for the source.
  • It must have an attribute matching the name of the accessor that can be used to set and retrieve and the value.
  • When any change is made to the value, a change notification will be emitted.

Reference

Bases: Source

:param value: :param accessor:

Source code in core/src/toga/sources/value_source.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class ValueSource(Source):
    """
    :param value:
    :param accessor:
    """

    def __init__(self, value: object = None, accessor: str = "value"):
        super().__init__()
        self.accessor = accessor
        setattr(self, accessor, value)

    def __str__(self) -> str:
        return str(getattr(self, self.accessor, None))

    def __setattr__(self, attr: str, value: object) -> None:
        super().__setattr__(attr, value)
        if attr == getattr(self, "accessor", None):
            self.notify("change", item=value)

Bases: Protocol, Generic[ItemT]

The protocol that must be implemented by objects that will act as a listener on a value data source.

Source code in core/src/toga/sources/base.py
10
11
12
13
14
15
16
17
18
19
20
@runtime_checkable
class ValueListener(Protocol, Generic[ItemT]):
    """The protocol that must be implemented by objects that will act as a listener on
    a value data source.
    """

    def source_change(self, *, item: ItemT) -> None:
        """A change has occurred in an item.

        :param item: The data object that has changed.
        """

source_change(*, item)

A change has occurred in an item.

:param item: The data object that has changed.

Source code in core/src/toga/sources/base.py
16
17
18
19
20
def source_change(self, *, item: ItemT) -> None:
    """A change has occurred in an item.

    :param item: The data object that has changed.
    """