Skip to content

Observer pattern #6

@davidbrochart

Description

@davidbrochart

In jupyter-widgets/ipywidgets#3293 (comment) @tlambert03 mentioned psygnal, that could be used to implement the equivalent of traitlets.
I think it is a good idea, but I'm not sure how it could fit here. For instance, take the Switch model, currently implemented as:

from .ypywidgets import Widget


class Switch(Widget):

    def __init__(self, value: bool = False, open_comm: bool = True) -> None:
        super().__init__(name="switch", open_comm=open_comm)
        self.yvalue = self.ydoc.get_map("value")
        self._set(value)

    def _set(self, value: bool) -> None:
        with self.ydoc.begin_transaction() as t:
            self.yvalue.set(t, "value",  value)

    @property
    def value(self) -> bool:
        return self.yvalue["value"]

    @value.setter
    def value(self, value: bool):
        if value == self.value:
            return

        self._set(value)

    def toggle(self):
        self.value = not self.value

Its YDoc consists of a YMap named value, with a single entry in it, also named value, which contains the boolean value of the switch. Here the observer pattern is manually implemented using a getter and a setter function for the value attribute.
If we were to use psygnal, we would need a way to point to the YDoc's structure (self.yvalue and value entry in it) from the psygnal's attribute.
I think that's the reason why traitlets use Python's descriptor protocol, which allows to get the name of an attribute at runtime.
Also, I'm not sure how we could connect nested YDoc structures (e.g. a YMap can contain other Y structures), but I don't think it was possible with traitlets anyway, so that would be an improvement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions