Skip to content

Instantly share code, notes, and snippets.

@GuillaumeDesforges
Created January 19, 2021 14:59
Show Gist options
  • Select an option

  • Save GuillaumeDesforges/de418e4df0f81d07e5943c1391b296bd to your computer and use it in GitHub Desktop.

Select an option

Save GuillaumeDesforges/de418e4df0f81d07e5943c1391b296bd to your computer and use it in GitHub Desktop.
simple Python observable implementation
T = TypeVar('T')
class Observable(Generic[T]):
def __init__(self, value: T) -> None:
self.value: T = value
# list of callable items
self.listeners: List[Callable[[T], Any]] = []
def update(self, new_value: T) -> None:
self.value = new_value
for listener in self.listeners:
listener(self.value)
a = Observable(0)
b = Observable(1)
a.listeners.append(lambda new_a: b + new_a)
b.listeners.append(lambda new_b: a - new_a)
# attention à pas créer des boucles infinies !
a.listeners.append(lambda new_a: b.update(b + new_a))
b.listeners.append(lambda new_b: a.update(a - new_b)) # does not terminate!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment