Skip to content

Commit

Permalink
implement compute method similar do depends_on
Browse files Browse the repository at this point in the history
  • Loading branch information
pLeminoq committed Dec 18, 2024
1 parent a001150 commit 6695df5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
3 changes: 2 additions & 1 deletion widget_state/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from .list_state import ListState
from .state import State
from .types import Serializable, Primitive
from .util import computed_state
from .util import computed_state, compute

__all__ = [
"BASIC_STATE_DICT",
Expand All @@ -36,4 +36,5 @@
"Primitive",
"computed_state",
"computed",
"compute",
]
18 changes: 17 additions & 1 deletion widget_state/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@

from __future__ import annotations

from typing import Any, Callable, ParamSpec, TypeVar
from typing import Any, Callable, Iterable, ParamSpec, TypeVar

from .basic_state import BasicState
from .state import State

T = TypeVar("T", bound=BasicState[Any])
P = ParamSpec("P")

S = TypeVar("S", bound=State)


def computed_state(
func: Callable[P, T],
Expand Down Expand Up @@ -64,3 +66,17 @@ def _on_change(_: Any) -> None:
return computed_value

return wrapped


def compute(
states: Iterable[State],
compute_value: Callable[[], S],
kwargs: dict[State, dict[str, Any]] = {},
) -> S:
res = compute_value()

for state in states:
_kwargs = {} if state not in kwargs else kwargs[state]
state.on_change(lambda _: res.copy_from(compute_value()), **_kwargs)

return res

0 comments on commit 6695df5

Please sign in to comment.