Atom: reactive values (Effect's effect/reactivity/Atom).
An atom is a recipe for a value; an AtomRegistry computes and holds
it while it is used. make(0) is a writable atom; make(lambda get: get(a) + 1) derives one (rebuilt when a changes); make(effect)
and make(stream) hold an AsyncResult of their progress. fn
makes a function atom run by writing an argument. runtime(layer)
makes atoms whose effects use a layer's services.
Combinators that keep an atom's kind are methods (atom.keep_alive(),
atom.map(f), atom.with_fallback(other)).
Re-exports#
Values#
| Attribute | Type | Description |
|---|---|---|
window_focus_signal | Atom[int] | Counts the times a browser window regained focus: with no window (Python has none), it stays 0, as Effect's does without one. |
Interrupt | InterruptSignal | Written to a function atom: interrupt the run in progress. |
Reset | ResetSignal | Written to a function atom: back to its initial value. |
runtime | RuntimeFactory | The default runtime factory. |
Types#
| Type | Definition | Description |
|---|---|---|
AtomResultFn | type AtomResultFn[Arg, A, E = Never] = Writable[AsyncResult[A, E], Arg | ResetSignal | InterruptSignal] | A function atom: write an argument to run it. |
PullResult | type PullResult[A, E = Never] = AsyncResult[PullChunk[A], E | NoSuchElementException] | |
Refresh | type Refresh = Callable[[Callable[[Atom[Any]], None]], None] | How an atom refreshes: it gets the registry's refresh, and refreshes the
atoms it stands for ( |
Classes#
Functions#
debounce#
debounce[A](atom, duration) -> Atom[A]| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] | |
duration | DurationInput |
Returns Atom[A]
def debounce[A](atom: Atom[A], duration: DurationInput) -> Atom[A]:
delay = from_input_unsafe(duration)
def read(get: AtomContext, source: Atom[A]) -> A:
cancel: list[Callable[[], None]] = []
value = [get.once(source)]
def fire() -> None:
cancel.clear()
get.set_self(value[0])
def stop() -> None:
if cancel:
cancel.pop()()
def on_change(next_value: A) -> None:
value[0] = next_value
stop()
cancel.append(get.registry.scheduler.call_later(delay, fire))
get.add_finalizer(stop)
get.subscribe(source, on_change)
return value[0]
return transform(atom, read, initial_value_target=atom)family#
family[K, T](f) -> Callable[[K], T]f memoized by argument (compared with Equal, so True is
not 1 and lists compare by their items); an atom nothing references
any more is dropped, and made again if asked for.
| Parameter | Type | Description |
|---|---|---|
f | Callable[[K], T] |
Returns Callable[[K], T]
def family[K, T](f: Callable[[K], T]) -> Callable[[K], T]:
"""``f`` memoized by argument (compared with ``Equal``, so ``True`` is
not ``1`` and lists compare by their items); an atom nothing references
any more is dropped, and made again if asked for."""
atoms: dict[Hashable, Callable[[], T | None]] = {}
def get(key: K) -> T:
slot = equal_key(key)
ref = atoms.get(slot)
found = None if ref is None else ref()
if found is not None:
return found
made = f(key)
try:
atoms[slot] = weakref.ref(made, lambda _: _drop(slot))
except TypeError:
atoms[slot] = lambda: made
return made
def _drop(slot: Hashable) -> None:
ref = atoms.get(slot)
if ref is not None and ref() is None:
del atoms[slot]
return getinitial_value#
initial_value[A](atom, value, *, skip_initial_run=False) -> InitialValue[A]A value to start a registry with (atom_registry.make( initial_values=[...])); with skip_initial_run an effect atom
keeps it instead of running its effect, until refreshed.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] | |
value | A | |
skip_initial_run | bool = False |
Returns InitialValue[A]
def initial_value[A](atom: Atom[A], value: A, *, skip_initial_run: bool = False) -> InitialValue[A]:
"""A value to start a registry with (``atom_registry.make(
initial_values=[...])``); with ``skip_initial_run`` an effect atom
keeps it instead of running its effect, until refreshed."""
return InitialValue(atom, value, skip_initial_run)make_refresh_on_signal#
make_refresh_on_signal(signal) -> Callable[[Atom[Any]], Atom[Any]]Refresh an atom whenever signal changes.
| Parameter | Type | Description |
|---|---|---|
signal | Atom[object] |
Returns Callable[[Atom[Any]], Atom[Any]]
def make_refresh_on_signal(signal: Atom[object]) -> Callable[[Atom[Any]], Atom[Any]]:
"""Refresh an atom whenever ``signal`` changes."""
def apply(atom: Atom[Any]) -> Atom[Any]:
def read(get: AtomContext, source: Atom[Any]) -> Any:
get.once(signal)
get.subscribe(signal, lambda _: get.refresh(source))
get.subscribe(source, get.set_self)
return get.once(source)
return transform(atom, read, initial_value_target=atom)
return applyrefresh_on_window_focus#
refresh_on_window_focus(atom) -> Atom[Any]| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
Returns Atom[Any]
def refresh_on_window_focus(atom: Atom[Any]) -> Atom[Any]:
return make_refresh_on_signal(window_focus_signal)(atom)set_idle_ttl#
set_idle_ttl[T: Atom[Any]](atom, duration) -> Tatom kept duration after it is last used (an infinite
duration keeps it alive).
| Parameter | Type | Description |
|---|---|---|
atom | T | |
duration | DurationInput |
Returns T
def set_idle_ttl[T: Atom[Any]](atom: T, duration: DurationInput) -> T:
"""``atom`` kept ``duration`` after it is last used (an infinite
duration keeps it alive)."""
parsed = from_input_unsafe(duration)
finite = parsed.is_finite()
return atom._with(kept_alive=not finite, idle_ttl=parsed if finite else None) # pyright: ignore[reportPrivateUsage]transform#
transform[A, W, B](atom: Writable[A, W], f: Callable[[AtomContext, Any], B], *, initial_value_target: Atom[B] | None = None) -> Writable[B, W]
transform[B](atom: Atom[Any], f: Callable[[AtomContext, Any], B], *, initial_value_target: Atom[B] | None = None) -> Atom[B]An atom read by f(get, atom); a writable atom's writes go
to it, and refreshing the result refreshes atom. Unused, it is
removed at once (no idle TTL).
| Parameter | Type | Description |
|---|---|---|
atom | ||
f | ||
initial_value_target | = None |
@overload
def transform[A, W, B](
atom: Writable[A, W],
f: Callable[[AtomContext, Any], B],
*,
initial_value_target: Atom[B] | None = None,
) -> Writable[B, W]: ...
@overload
def transform[B](
atom: Atom[Any],
f: Callable[[AtomContext, Any], B],
*,
initial_value_target: Atom[B] | None = None,
) -> Atom[B]: ...
def transform(
atom: Atom[Any],
f: Callable[[AtomContext, Any], Any],
*,
initial_value_target: Atom[Any] | None = None,
) -> Atom[Any]:
"""An atom read by ``f(get, atom)``; a writable ``atom``'s writes go
to it, and refreshing the result refreshes ``atom``. Unused, it is
removed at once (no idle TTL)."""
def read(get: AtomContext) -> Any:
return f(get, atom)
derived: Atom[Any]
if isinstance(atom, Writable):
source = cast("Writable[Any, Any]", atom)
def write(ctx: WriteContext[Any], value: Any) -> None:
ctx.set(source, value)
derived = Writable(read, write, _refresh_of(source))
else:
derived = readable(read, _refresh_of(atom))
derived = remove_ttl(derived)
if initial_value_target is not None:
derived.initial_value_target = _target(initial_value_target)
return derivedwith_fallback#
with_fallback(atom, fallback) -> AnyWhile atom is Initial, fallback's result, waiting.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[AsyncResult[Any, Any]] | |
fallback | Atom[AsyncResult[Any, Any]] |
Returns Any
def with_fallback(atom: Atom[AsyncResult[Any, Any]], fallback: Atom[AsyncResult[Any, Any]]) -> Any:
"""While ``atom`` is ``Initial``, ``fallback``'s result, waiting."""
def read(get: AtomContext) -> AsyncResult[Any, Any]:
result = get(atom)
if isinstance(result, Initial):
return async_result.waiting(get(fallback))
return result
if isinstance(atom, Writable):
source = cast("Writable[Any, Any]", atom)
def write(ctx: WriteContext[Any], value: Any) -> None:
ctx.set(source, value)
return Writable(read, write, _refresh_of(source))
return readable(read, _refresh_of(atom))with_refresh#
with_refresh[A](atom, duration) -> Atom[A]| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] | |
duration | DurationInput |
Returns Atom[A]
def with_refresh[A](atom: Atom[A], duration: DurationInput) -> Atom[A]:
delay = from_input_unsafe(duration)
def read(get: AtomContext, source: Atom[A]) -> A:
cancel = get.registry.scheduler.call_later(delay, lambda: get.refresh(source))
get.add_finalizer(cancel)
return get(source)
return transform(atom, read, initial_value_target=atom)make#
make[A, E = Never](effect: Effect[A, E, Scope | AtomRegistry], /, *, initial_value: A = ..., uninterruptible: bool = False) -> Atom[AsyncResult[A, E]]
make[A, E = Never](stream: Stream[A, E, AtomRegistry], /, *, initial_value: A = ...) -> Atom[AsyncResult[A, E | NoSuchElementException]]
make[A, E = Never](create: Callable[[AtomContext], Effect[A, E, Scope | AtomRegistry]], /, *, initial_value: A = ..., uninterruptible: bool = False) -> Atom[AsyncResult[A, E]]
make[A, E = Never](create: Callable[[AtomContext], Stream[A, E, AtomRegistry]], /, *, initial_value: A = ...) -> Atom[AsyncResult[A, E | NoSuchElementException]]
make[A](create: Callable[[AtomContext], A], /) -> Atom[A]
make(effect: Effect[Any, Any, Any] | Stream[Any, Any, Any], /, *, initial_value: Any = ..., uninterruptible: bool = False) -> Never
make[A](initial: A, /) -> Writable[A, A]An atom of arg:
- an
Effect(needing at mostScopeandAtomRegistry): anAsyncResultof it, run when the atom is built (initial_valueis shown, as a success, until it finishes); - a
Stream: anAsyncResultof its latest item, waiting until it ends (an empty one fails withNoSuchElementException); - a function of an
AtomContext: a derived atom, rebuilt when what it read changes (an effect or stream it returns is run as above); - anything else: a writable atom holding that value.
| Parameter | Type | Description |
|---|---|---|
arg | ||
initial_value | = MISSING | |
uninterruptible | = False |
@overload
def make[A, E = Never](
effect: Effect[A, E, Scope | AtomRegistry],
/,
*,
initial_value: A = ...,
uninterruptible: bool = False,
) -> Atom[AsyncResult[A, E]]: ...
@overload
def make[A, E = Never](
stream: Stream[A, E, AtomRegistry], /, *, initial_value: A = ...
) -> Atom[AsyncResult[A, E | NoSuchElementException]]: ...
@overload
def make[A, E = Never](
create: Callable[[AtomContext], Effect[A, E, Scope | AtomRegistry]],
/,
*,
initial_value: A = ...,
uninterruptible: bool = False,
) -> Atom[AsyncResult[A, E]]: ...
@overload
def make[A, E = Never](
create: Callable[[AtomContext], Stream[A, E, AtomRegistry]],
/,
*,
initial_value: A = ...,
) -> Atom[AsyncResult[A, E | NoSuchElementException]]: ...
@overload
def make[A](create: Callable[[AtomContext], A], /) -> Atom[A]: ... # pyright: ignore[reportOverlappingOverload]
@overload
@deprecated("it needs services an atom cannot provide: build it with a runtime's atom()")
def make(
effect: Effect[Any, Any, Any] | Stream[Any, Any, Any],
/,
*,
initial_value: Any = ...,
uninterruptible: bool = False,
) -> Never: ...
@overload
def make[A](initial: A, /) -> Writable[A, A]: ...
def make(arg: object, /, *, initial_value: object = MISSING, uninterruptible: bool = False) -> Any:
"""An atom of ``arg``:
- an ``Effect`` (needing at most ``Scope`` and ``AtomRegistry``): an
``AsyncResult`` of it, run when the atom is built (``initial_value``
is shown, as a success, until it finishes);
- a ``Stream``: an ``AsyncResult`` of its latest item, waiting until it
ends (an empty one fails with ``NoSuchElementException``);
- a function of an ``AtomContext``: a derived atom, rebuilt when what
it read changes (an effect or stream it returns is run as above);
- anything else: a writable atom holding that value.
"""
read = make_read(arg, initial_option(initial_value), uninterruptible)
if not callable(read):
return read
return readable(lambda get: read(get, _EMPTY))get#
get[A](atom) -> Effect[A, Never, AtomRegistry]| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] |
Returns Effect[A, Never, AtomRegistry]
def get[A](atom: Atom[A]) -> Effect[A, Never, AtomRegistry]:
return _registry().map(lambda r: r.get(atom))get_result#
get_result[A, E](atom, *, suspend_on_waiting=False) -> Effect[A, E, AtomRegistry]The atom's success or failure, once it has one.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[AsyncResult[A, E]] | |
suspend_on_waiting | bool = False |
Returns Effect[A, E, AtomRegistry]
def get_result[A, E](
atom: Atom[AsyncResult[A, E]], *, suspend_on_waiting: bool = False
) -> Effect[A, E, AtomRegistry]:
"""The atom's success or failure, once it has one."""
return _registry().flat_map(
lambda r: atom_registry.get_result(r, atom, suspend_on_waiting=suspend_on_waiting)
)modify#
modify[R, W, A](atom, f) -> Effect[A, Never, AtomRegistry]| Parameter | Type | Description |
|---|---|---|
atom | Writable[R, W] | |
f | Callable[[R], tuple[A, W]] |
Returns Effect[A, Never, AtomRegistry]
def modify[R, W, A](
atom: Writable[R, W], f: Callable[[R], tuple[A, W]]
) -> Effect[A, Never, AtomRegistry]:
return _registry().map(lambda r: r.modify(atom, f))mount#
mount(atom) -> Effect[None, Never, AtomRegistry | Scope]Keep atom mounted until the current scope closes.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
Returns Effect[None, Never, AtomRegistry | Scope]
def mount(atom: Atom[Any]) -> Effect[None, Never, AtomRegistry | Scope]:
"""Keep ``atom`` mounted until the current scope closes."""
return _registry().flat_map(lambda r: atom_registry.mount(r, atom))refresh#
refresh(atom) -> Effect[None, Never, AtomRegistry]| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
Returns Effect[None, Never, AtomRegistry]
def refresh(atom: Atom[Any]) -> Effect[None, Never, AtomRegistry]:
return _registry().map(lambda r: r.refresh(atom))set#
set[W](atom, value) -> Effect[None, Never, AtomRegistry]| Parameter | Type | Description |
|---|---|---|
atom | Writable[Any, W] | |
value | W |
Returns Effect[None, Never, AtomRegistry]
def set[W](atom: Writable[Any, W], value: W) -> Effect[None, Never, AtomRegistry]:
return _registry().map(lambda r: r.set(atom, value))to_stream#
to_stream[A](atom) -> Stream[A, Never, AtomRegistry]| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] |
Returns Stream[A, Never, AtomRegistry]
def to_stream[A](atom: Atom[A]) -> Stream[A, Never, AtomRegistry]:
from pyfect import stream
return stream.unwrap(_registry().map(lambda r: atom_registry.to_stream(r, atom)))to_stream_result#
to_stream_result[A, E](atom) -> Stream[A, E, AtomRegistry]| Parameter | Type | Description |
|---|---|---|
atom | Atom[AsyncResult[A, E]] |
Returns Stream[A, E, AtomRegistry]
def to_stream_result[A, E](atom: Atom[AsyncResult[A, E]]) -> Stream[A, E, AtomRegistry]:
from pyfect import stream
return stream.unwrap(_registry().map(lambda r: atom_registry.to_stream_result(r, atom)))update#
update[R, W](atom, f) -> Effect[None, Never, AtomRegistry]| Parameter | Type | Description |
|---|---|---|
atom | Writable[R, W] | |
f | Callable[[R], W] |
Returns Effect[None, Never, AtomRegistry]
def update[R, W](atom: Writable[R, W], f: Callable[[R], W]) -> Effect[None, Never, AtomRegistry]:
return _registry().map(lambda r: r.update(atom, f))fn#
fn[Arg, A, E = Never](f: Callable[[Arg, FnContext], Effect[A, E, Scope | AtomRegistry]], /, *, initial_value: A = ..., concurrent: bool = False) -> AtomResultFn[Arg, A, E]
fn[Arg, A, E = Never](f: Callable[[Arg, FnContext], Stream[A, E, AtomRegistry]], /, *, initial_value: A = ..., concurrent: bool = False) -> AtomResultFn[Arg, A, E | NoSuchElementException]A function atom: writing arg runs f(arg, get)'s effect (or
stream), and the atom holds its AsyncResult. Writing again
interrupts the run in progress (unless concurrent, which keeps
every run and settles with the first); Reset and Interrupt
restore the initial value or interrupt.
| Parameter | Type | Description |
|---|---|---|
f | ||
initial_value | = MISSING | |
concurrent | = False |
@overload
def fn[Arg, A, E = Never](
f: Callable[[Arg, FnContext], Effect[A, E, Scope | AtomRegistry]],
/,
*,
initial_value: A = ...,
concurrent: bool = False,
) -> AtomResultFn[Arg, A, E]: ...
@overload
def fn[Arg, A, E = Never](
f: Callable[[Arg, FnContext], Stream[A, E, AtomRegistry]],
/,
*,
initial_value: A = ...,
concurrent: bool = False,
) -> AtomResultFn[Arg, A, E | NoSuchElementException]: ...
def fn(
f: Callable[[Any, FnContext], Any],
/,
*,
initial_value: object = MISSING,
concurrent: bool = False,
) -> Writable[Any, Any]:
"""A function atom: writing ``arg`` runs ``f(arg, get)``'s effect (or
stream), and the atom holds its ``AsyncResult``. Writing again
interrupts the run in progress (unless ``concurrent``, which keeps
every run and settles with the first); ``Reset`` and ``Interrupt``
restore the initial value or interrupt."""
read, write, _ = make_result_fn(f, initial_option(initial_value), concurrent)
empty: Context[Never] = Context.empty()
return writable(lambda get: read(get, empty), write)fn_sync#
fn_sync[Arg, A](f: Callable[[Arg, FnContext], A], /) -> Writable[Option[A], Arg]
fn_sync[Arg, A](f: Callable[[Arg, FnContext], A], /, *, initial_value: A) -> Writable[A, Arg]A function atom running f when written: it holds Some of
the last result (None before the first write), or the result
itself with an initial_value.
| Parameter | Type | Description |
|---|---|---|
f | ||
initial_value | = MISSING |
@overload
def fn_sync[Arg, A](f: Callable[[Arg, FnContext], A], /) -> Writable[Option[A], Arg]: ...
@overload
def fn_sync[Arg, A](
f: Callable[[Arg, FnContext], A], /, *, initial_value: A
) -> Writable[A, Arg]: ...
def fn_sync(
f: Callable[[Any, FnContext], Any], /, *, initial_value: object = MISSING
) -> Writable[Any, Any]:
"""A function atom running ``f`` when written: it holds ``Some`` of
the last result (``None`` before the first write), or the result
itself with an ``initial_value``."""
arg_atom: Writable[_Call[Any], _Call[Any]] = remove_ttl(state(_Call[Any](0, None)))
has_initial = initial_value is not MISSING
def read(get: AtomContext) -> Any:
ctx = _fn_context(get)
call = get.get(arg_atom)
if call.counter == 0:
return initial_value if has_initial else None
result = f(call.arg, ctx)
return result if has_initial else Some(result)
def write(ctx: WriteContext[Any], arg: Any) -> None:
def body() -> None:
ctx.set(arg_atom, _Call(ctx.get(arg_atom).counter + 1, arg))
ctx.refresh_self()
batch(body)
return writable(read, write)pull#
pull[A, E = Never](create, *, disable_accumulation=False) -> Writable[PullResult[A, E], None]An atom reading create's stream a chunk at a time: built, it
pulls the first chunk; each write (None) pulls the next.
| Parameter | Type | Description |
|---|---|---|
create | Stream[A, E, AtomRegistry] | Callable[[AtomContext], Stream[A, E, AtomRegistry]] | |
disable_accumulation | bool = False |
Returns Writable[PullResult[A, E], None]
def pull[A, E = Never](
create: Stream[A, E, AtomRegistry] | Callable[[AtomContext], Stream[A, E, AtomRegistry]],
*,
disable_accumulation: bool = False,
) -> Writable[PullResult[A, E], None]:
"""An atom reading ``create``'s stream a chunk at a time: built, it
pulls the first chunk; each write (``None``) pulls the next."""
pull_signal: Writable[int, int] = remove_ttl(state(0))
def create_effect(get: AtomContext) -> Effect[PullChunk[Any], Any, Any]:
return make_stream_pull_effect(get, pull_signal, create, disable_accumulation)
read = cast("Callable[[AtomContext, Context[Any]], Any]", make_read(create_effect, None, False))
empty: Context[Never] = Context.empty()
return make_stream_pull(pull_signal, readable(lambda get: read(get, empty)))kvs#
kvs[T](*, runtime: AtomRuntime[KeyValueStore, Any], key: str, schema: Codec[T, Any, Any, Any], default_value: Callable[[], T], mode: Literal['sync'] = 'sync') -> Writable[T, T]
kvs[T](*, runtime: AtomRuntime[KeyValueStore, Any], key: str, schema: Codec[T, Any, Any, Any], default_value: Callable[[], T], mode: Literal['async']) -> Writable[AsyncResult[T, Any], T]An atom holding the value stored under key (default_value()
until one is, and written back then); writes are stored. "sync"
shows the default until the store answers; "async" holds an
AsyncResult.
| Parameter | Type | Description |
|---|---|---|
runtime | ||
key | ||
schema | ||
default_value | ||
mode | = 'sync' |
@overload
def kvs[T](
*,
runtime: AtomRuntime[KeyValueStore, Any],
key: str,
schema: Codec[T, Any, Any, Any],
default_value: Callable[[], T],
mode: Literal["sync"] = "sync",
) -> Writable[T, T]: ...
@overload
def kvs[T](
*,
runtime: AtomRuntime[KeyValueStore, Any],
key: str,
schema: Codec[T, Any, Any, Any],
default_value: Callable[[], T],
mode: Literal["async"],
) -> Writable[AsyncResult[T, Any], T]: ...
def kvs(
*,
runtime: AtomRuntime[KeyValueStore, Any],
key: str,
schema: Codec[Any, Any, Any, Any],
default_value: Callable[[], Any],
mode: Literal["sync", "async"] = "sync",
) -> Writable[Any, Any]:
"""An atom holding the value stored under ``key`` (``default_value()``
until one is, and written back then); writes are stored. ``"sync"``
shows the default until the store answers; ``"async"`` holds an
``AsyncResult``."""
from pyfect.persistence.key_value_store import KeyValueStore
def store_value(value: Any, _get: FnContext) -> Any:
return KeyValueStore().flat_map(lambda s: s.to_schema_store(schema).set(key, value))
set_atom = runtime.fn(store_value)
result_atom = runtime.atom(
KeyValueStore().flat_map(lambda s: s.to_schema_store(schema).get(key))
)
def read_async(get: AtomContext) -> Any:
get.mount(set_atom)
def mapper(result: AsyncResult[Option[Any], Any]) -> AsyncResult[Any, Any]:
def or_default(found: Option[Any]) -> Any:
if found is not None:
return found.value
value = default_value()
get.set(set_atom, value)
return value
return async_result.map(result, or_default)
get.subscribe(result_atom, lambda result: get.set_self(mapper(result)))
return mapper(get.once(result_atom))
def read_sync(get: AtomContext) -> Any:
get.mount(set_atom)
def on_result(result: AsyncResult[Option[Any], Any]) -> None:
if not isinstance(result, Success):
return
found: Option[Any] = result.value
if found is not None:
get.set_self(found.value)
else:
current = get.self()
value = default_value() if current is None else current.value
get.set_self(value)
get.set(set_atom, value)
get.subscribe(result_atom, on_result, immediate=True)
current = get.self()
return default_value() if current is None else current.value
def write(ctx: WriteContext[Any], value: Any) -> None:
ctx.set(set_atom, value)
ctx.set_self(async_result.success(value) if mode == "async" else value)
return writable(read_async if mode == "async" else read_sync, write)optimistic#
optimistic[A](atom) -> Writable[A, Transition[A]]| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] |
Returns Writable[A, Transition[A]]
def optimistic[A](atom: Atom[A]) -> Writable[A, Transition[A]]:
counter = itertools.count(1)
write_atom = remove_ttl(state(cast("tuple[int, Transition[A] | None]", (0, None))))
def read(get: AtomContext) -> A:
last = [get.once(atom)]
needs_refresh = [False]
transitions: dict[Transition[A], None] = {}
cancels: dict[Callable[[], None], None] = {}
def on_source(value: A) -> None:
last[0] = value
if transitions:
return
needs_refresh[0] = False
if _shows(cast("Any", get.self()).value, value):
get.set_self(value)
get.subscribe(atom, on_source)
def on_write(entry: tuple[int, Transition[A] | None]) -> None:
transition = entry[1]
if transition is None or transition in transitions:
return
transitions[transition] = None
handle: list[Callable[[], None]] = []
def on_result(result: AsyncResult[A, object]) -> None:
if isinstance(result, Success) and result.waiting:
get.set_self(result.value)
return
transitions.pop(transition, None)
if handle:
cancels.pop(handle[0], None)
handle[0]()
if not needs_refresh[0] and not async_result.is_failure(result):
needs_refresh[0] = True
if not transitions:
if needs_refresh[0]:
needs_refresh[0] = False
get.refresh(atom)
else:
get.set_self(last[0])
cancel = get.registry.subscribe(transition, on_result, immediate=True)
if transition in transitions:
handle.append(cancel)
cancels[cancel] = None
else:
cancel()
get.subscribe(write_atom, on_write)
def finalize() -> None:
for cancel in list(cancels):
cancel()
transitions.clear()
cancels.clear()
get.add_finalizer(finalize)
return last[0]
def write(ctx: WriteContext[Any], transition: Transition[A]) -> None:
ctx.set(write_atom, (next(counter), transition))
return writable(read, write, lambda refresh: refresh(atom))optimistic_fn#
optimistic_fn[A, W, OW, XA, XE](atom, *, reducer, fn) -> AtomResultFn[OW, XA, XE]A function atom running fn as a transition of atom: the
atom shows reducer(current, arg) (and what fn reports through
the setter it gets) until fn finishes.
| Parameter | Type | Description |
|---|---|---|
atom | Writable[A, Transition[W]] | |
reducer | Callable[[A, OW], W] | |
fn | AtomResultFn[OW, XA, XE] | Callable[[Callable[[W], None]], AtomResultFn[OW, XA, XE]] |
Returns AtomResultFn[OW, XA, XE]
def optimistic_fn[A, W, OW, XA, XE](
atom: Writable[A, Transition[W]],
*,
reducer: Callable[[A, OW], W],
fn: AtomResultFn[OW, XA, XE] | Callable[[Callable[[W], None]], AtomResultFn[OW, XA, XE]],
) -> AtomResultFn[OW, XA, XE]:
"""A function atom running ``fn`` as a transition of ``atom``: the
atom shows ``reducer(current, arg)`` (and what ``fn`` reports through
the setter it gets) until ``fn`` finishes."""
transition: Writable[AsyncResult[W, object], AsyncResult[W, object]] = remove_ttl(
state(cast("AsyncResult[W, object]", async_result.initial()))
)
make_fn = fn
def run(arg: OW, get: FnContext) -> Effect[XA, XE]:
value: Any = reducer(get(atom), arg)
if async_result.is_async_result(value):
value = async_result.waiting(value, touch=True)
get.set(transition, async_result.success(value, waiting=True))
get.set(atom, transition)
if isinstance(make_fn, Writable):
target = cast("AtomResultFn[OW, XA, XE]", make_fn)
else:
def report(result: W) -> None:
shown: Any = result
if async_result.is_async_result(shown):
shown = async_result.waiting(shown)
get.set(transition, async_result.success(shown, waiting=True))
target = make_fn(report).auto_dispose()
get.set(target, arg)
def register(resume: Callable[[Effect[XA, XE]], None]) -> None:
def on_result(result: AsyncResult[XA, XE]) -> None:
if isinstance(result, Initial) or result.waiting:
return
get.set(transition, async_result.map(result, lambda _: value))
resume(result_effect(result))
get.subscribe(target, on_result, immediate=True)
return callback(register)
return _fn(run)context#
context(*, memo_map=None) -> RuntimeFactoryA runtime factory: its runtimes share memo_map (by default one
per registry) and its global layer.
| Parameter | Type | Description |
|---|---|---|
memo_map | Atom[MemoMap] | MemoMap | None = None |
Returns RuntimeFactory
def context(*, memo_map: Atom[MemoMap] | MemoMap | None = None) -> RuntimeFactory:
"""A runtime factory: its runtimes share ``memo_map`` (by default one
per registry) and its global layer."""
return RuntimeFactory(memo_map)with_reactivity#
with_reactivity[T: Atom[Any]](keys) -> Callable[[T], T]runtime.with_reactivity(keys).
| Parameter | Type | Description |
|---|---|---|
keys | Keys |
Returns Callable[[T], T]
def with_reactivity[T: Atom[Any]](keys: Keys) -> Callable[[T], T]:
"""``runtime.with_reactivity(keys)``."""
return runtime.with_reactivity(keys)get_server_value#
get_server_value[A](atom, registry) -> AThe atom's server value if it has one, else its value.
| Parameter | Type | Description |
|---|---|---|
atom | Atom[A] | |
registry | AtomRegistryService |
Returns A
def get_server_value[A](atom: Atom[A], registry: AtomRegistryService) -> A:
"""The atom's server value if it has one, else its value."""
if atom.server_value is not None:
return cast("A", atom.server_value(registry.get))
return registry.get(atom)is_serializable#
is_serializable(atom) -> bool| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
Returns bool
def is_serializable(atom: Atom[Any]) -> bool:
return atom.serializable_info is not Noneserializable#
serializable[T: Atom[Any]](atom, *, key, schema, skip_initial_run=False) -> T| Parameter | Type | Description |
|---|---|---|
atom | T | |
key | str | |
schema | Codec[Any, Any, Never, Never] | |
skip_initial_run | bool = False |
Returns T
def serializable[T: Atom[Any]](
atom: T, *, key: str, schema: Codec[Any, Any, Never, Never], skip_initial_run: bool = False
) -> T:
from pyfect.reactivity.atom._combinators import label_site
from pyfect.schema import decode_sync, encode_sync, to_codec_json
codec = cast("Codec[Any, Any, Never, Never]", to_codec_json(schema))
info = SerializableInfo(key, encode_sync(codec), decode_sync(codec), skip_initial_run)
label = atom.label if atom.label is not None else (key, label_site(3))
return atom._with(serializable_info=info, label=label) # pyright: ignore[reportPrivateUsage]with_server_value_initial#
with_server_value_initial[T: Atom[Any]](atom) -> Twith_server_value of a waiting Initial.
| Parameter | Type | Description |
|---|---|---|
atom | T |
Returns T
def with_server_value_initial[T: Atom[Any]](atom: T) -> T:
"""``with_server_value`` of a waiting ``Initial``."""
return atom._with(server_value=_initial_waiting) # pyright: ignore[reportPrivateUsage]subscription_ref#
subscription_ref[A](ref: SubscriptionRef[A] | Callable[[AtomContext], SubscriptionRef[A]], /) -> Writable[A, A]
subscription_ref[A, E = Never](effect: Effect[SubscriptionRef[A], E, Scope | AtomRegistry] | Callable[[AtomContext], Effect[SubscriptionRef[A], E, Scope | AtomRegistry]], /) -> Writable[AsyncResult[A, E], A]An atom holding the value of a SubscriptionRef (or of the one an
effect makes, as an AsyncResult); writing it sets the ref.
| Parameter | Type | Description |
|---|---|---|
ref |
@overload
def subscription_ref[A](
ref: SubscriptionRef[A] | Callable[[AtomContext], SubscriptionRef[A]], /
) -> Writable[A, A]: ...
@overload
def subscription_ref[A, E = Never](
effect: Effect[SubscriptionRef[A], E, Scope | AtomRegistry]
| Callable[[AtomContext], Effect[SubscriptionRef[A], E, Scope | AtomRegistry]],
/,
) -> Writable[AsyncResult[A, E], A]: ...
def subscription_ref(ref: Any, /) -> Writable[Any, Any]:
"""An atom holding the value of a ``SubscriptionRef`` (or of the one an
effect makes, as an ``AsyncResult``); writing it sets the ref."""
from pyfect.reactivity.atom._types import readable
return make_sub_ref(readable(ref_atom_read(ref)), read_subscription_ref)swr#
swr[A, E](atom, *, stale_time, revalidate_on_mount=True, revalidate_on_focus=False, focus_signal=None) -> Atom[AsyncResult[A, E]]| Parameter | Type | Description |
|---|---|---|
atom | Atom[AsyncResult[A, E]] | |
stale_time | DurationInput | |
revalidate_on_mount | bool = True | |
revalidate_on_focus | bool | Literal['always'] = False | |
focus_signal | Atom[object] | None = None |
Returns Atom[AsyncResult[A, E]]
def swr[A, E](
atom: Atom[AsyncResult[A, E]],
*,
stale_time: DurationInput,
revalidate_on_mount: bool = True,
revalidate_on_focus: bool | Literal["always"] = False,
focus_signal: Atom[object] | None = None,
) -> Atom[AsyncResult[A, E]]:
stale = to_millis(from_input_unsafe(stale_time))
def read(get: AtomContext, source: Atom[AsyncResult[A, E]]) -> AsyncResult[A, E]:
current = get.once(source)
get.subscribe(source, get.set_self)
if revalidate_on_focus and focus_signal is not None:
get.once(focus_signal)
def on_focus(_: object) -> None:
if revalidate_on_focus == "always" or _should_revalidate(get.once(source), stale):
get.refresh(source)
get.subscribe(focus_signal, on_focus)
first_read = get.self() is None
if first_read and not revalidate_on_mount:
return current
if _should_revalidate(current, stale):
active = [True]
get.add_finalizer(lambda: active.__setitem__(0, False))
def revalidate() -> None:
if active[0] and _should_revalidate(get.once(source), stale):
get.refresh(source)
get.registry.scheduler.schedule(revalidate)
return current
return transform(atom, read, initial_value_target=atom)is_atom#
is_atom(u) -> bool| Parameter | Type | Description |
|---|---|---|
u | object |
Returns bool
def is_atom(u: object) -> bool:
return isinstance(u, Atom)is_writable#
is_writable(atom) -> bool| Parameter | Type | Description |
|---|---|---|
atom | Atom[Any] |
Returns bool
def is_writable(atom: Atom[Any]) -> bool:
return isinstance(atom, Writable)readable#
readable[A](read, refresh=None) -> Atom[A]An atom computed by read.
| Parameter | Type | Description |
|---|---|---|
read | Callable[[AtomContext], A] | |
refresh | Refresh | None = None |
Returns Atom[A]
def readable[A](read: Callable[[AtomContext], A], refresh: Refresh | None = None) -> Atom[A]:
"""An atom computed by ``read``."""
return Atom(read, refresh)writable#
writable[R, W](read, write, refresh=None) -> Writable[R, W]An atom computed by read that takes writes through write.
| Parameter | Type | Description |
|---|---|---|
read | Callable[[AtomContext], R] | |
write | Callable[[WriteContext[R], W], None] | |
refresh | Refresh | None = None |
Returns Writable[R, W]
def writable[R, W](
read: Callable[[AtomContext], R],
write: Callable[[WriteContext[R], W], None],
refresh: Refresh | None = None,
) -> Writable[R, W]:
"""An atom computed by ``read`` that takes writes through ``write``."""
return Writable(read, write, refresh)On This Page
Re-exportsValuesTypesClassesFunctionsdebouncefamilyinitial_valuemake_refresh_on_signalrefresh_on_window_focusset_idle_ttltransformwith_fallbackwith_refreshmakegetget_resultmodifymountrefreshsetto_streamto_stream_resultupdatefnfn_syncpullkvsoptimisticoptimistic_fncontextwith_reactivityget_server_valueis_serializableserializablewith_server_value_initialsubscription_refswris_atomis_writablereadablewritable