AtomRegistry: where atoms' values live (Effect's
effect/reactivity/AtomRegistry).
make() creates a registry (AtomRegistryService); layer
provides one as the AtomRegistry service and disposes it with the
layer's scope. r.get(atom), r.set(atom, value),
r.subscribe(atom, f) and r.mount(atom) work on it directly; the
effect-returning to_stream, get_result and mount take the
registry as their first argument.
A registry runs node removals, idle timeouts and the fibers of atoms
backed by effects on one Scheduler: the one given, else the running
fiber's, else the running asyncio loop's.
Values#
| Attribute | Type | Description |
|---|---|---|
layer | Layer[AtomRegistry] | Provides a registry with the default options. |
Types#
| Type | Definition | Description |
|---|---|---|
NodeState | type NodeState = Literal['uninitialized', 'stale', 'valid', 'removed'] |
Classes#
Functions#
is_atom_registry#
is_atom_registry(u) -> bool| Parameter | Type | Description |
|---|---|---|
u | object |
Returns bool
def is_atom_registry(u: object) -> bool:
return isinstance(u, AtomRegistryService)make#
make(*, initial_values=None, scheduler=None, timeout_resolution=None, default_idle_ttl=None) -> AtomRegistryServiceA new registry. initial_values seed atoms (atom.initial_value);
default_idle_ttl keeps unused atoms that long, checked every
timeout_resolution (half the TTL by default, else a second).
Without scheduler it runs on the running fiber's scheduler, else
the running asyncio loop's (NoRunError with neither).
| Parameter | Type | Description |
|---|---|---|
initial_values | Iterable[InitialValue[Any]] | None = None | |
scheduler | Scheduler | None = None | |
timeout_resolution | DurationInput | None = None | |
default_idle_ttl | DurationInput | None = None |
Returns AtomRegistryService
def make(
*,
initial_values: Iterable[InitialValue[Any]] | None = None,
scheduler: Scheduler | None = None,
timeout_resolution: DurationInput | None = None,
default_idle_ttl: DurationInput | None = None,
) -> AtomRegistryService:
"""A new registry. ``initial_values`` seed atoms (``atom.initial_value``);
``default_idle_ttl`` keeps unused atoms that long, checked every
``timeout_resolution`` (half the TTL by default, else a second).
Without ``scheduler`` it runs on the running fiber's scheduler, else
the running asyncio loop's (``NoRunError`` with neither)."""
return AtomRegistryService(
initial_values=initial_values,
scheduler=scheduler,
timeout_resolution=timeout_resolution,
default_idle_ttl=default_idle_ttl,
)layer_options#
layer_options(*, initial_values=None, scheduler=None, timeout_resolution=None, default_idle_ttl=None) -> Layer[AtomRegistry]A layer providing a registry made with these options (on the building fiber's scheduler by default), disposed with its scope.
| Parameter | Type | Description |
|---|---|---|
initial_values | Iterable[InitialValue[Any]] | None = None | |
scheduler | Scheduler | None = None | |
timeout_resolution | DurationInput | None = None | |
default_idle_ttl | DurationInput | None = None |
Returns Layer[AtomRegistry]
def layer_options(
*,
initial_values: Iterable[InitialValue[Any]] | None = None,
scheduler: Scheduler | None = None,
timeout_resolution: DurationInput | None = None,
default_idle_ttl: DurationInput | None = None,
) -> Layer[AtomRegistry]:
"""A layer providing a registry made with these options (on the
building fiber's scheduler by default), disposed with its scope."""
def build(scope: CloseableScope) -> Effect[AtomRegistryService]:
def create() -> AtomRegistryService:
return make(
initial_values=initial_values,
scheduler=scheduler,
timeout_resolution=timeout_resolution,
default_idle_ttl=default_idle_ttl,
)
def register(registry: AtomRegistryService) -> Effect[AtomRegistryService]:
return scope.add_finalizer(lambda _exit: _Sync(registry.dispose)).as_(registry)
return _Sync(create).flat_map(register)
return layer_effect(AtomRegistry, Scope().flat_map(build))to_stream#
to_stream[A](self, atom) -> Stream[A]The atom's current value, then each new one.
| Parameter | Type | Description |
|---|---|---|
self | AtomRegistryService | |
atom | Atom[A] |
Returns Stream[A]
def to_stream[A](self: AtomRegistryService, atom: Atom[A]) -> Stream[A]:
"""The atom's current value, then each new one."""
from pyfect import stream
def start(queue: Queue[A, Done]) -> Effect[None, Never, Scope]:
def offer(value: A) -> None:
queue.offer_unsafe(value)
def body(fiber: Fiber[Any, Any]) -> Effect[None]:
scope = fiber._context.get_unsafe(Scope)
cancel = self.subscribe(atom, offer, immediate=True)
return scope.add_finalizer(lambda _: _Sync(cancel))
return _WithFiber(body)
return stream.callback(start)to_stream_result#
to_stream_result[A, E](self, atom) -> Stream[A, E]The values of an atom holding a result: initial results are skipped, a failure fails the stream, and repeated values are dropped.
| Parameter | Type | Description |
|---|---|---|
self | AtomRegistryService | |
atom | Atom[AsyncResult[A, E]] |
Returns Stream[A, E]
def to_stream_result[A, E](
self: AtomRegistryService, atom: Atom[AsyncResult[A, E]]
) -> Stream[A, E]:
"""The values of an atom holding a result: initial results are skipped,
a failure fails the stream, and repeated values are dropped."""
return (
to_stream(self, atom)
.filter(async_result.is_not_initial)
.map_effect(result_effect)
.changes()
)get_result#
get_result[A, E](self, atom, *, suspend_on_waiting=False) -> Effect[A, E]The atom's success or failure, once it is not Initial (nor
waiting, with suspend_on_waiting).
| Parameter | Type | Description |
|---|---|---|
self | AtomRegistryService | |
atom | Atom[AsyncResult[A, E]] | |
suspend_on_waiting | bool = False |
Returns Effect[A, E]
def get_result[A, E](
self: AtomRegistryService,
atom: Atom[AsyncResult[A, E]],
*,
suspend_on_waiting: bool = False,
) -> Effect[A, E]:
"""The atom's success or failure, once it is not ``Initial`` (nor
waiting, with ``suspend_on_waiting``)."""
def ready(result: AsyncResult[A, E]) -> bool:
return not isinstance(result, Initial) and not (suspend_on_waiting and result.waiting)
def register(resume: Callable[[Effect[A, E]], None]) -> Effect[None] | None:
result = self.get(atom)
if ready(result):
resume(result_effect(result))
return None
cancel = Unsubscribe()
def on_change(value: AsyncResult[A, E]) -> None:
if ready(value):
resume(result_effect(value))
cancel()
cancel.set(self.subscribe(atom, on_change))
return _Sync(cancel)
return _Callback(register)mount#
mount(self, atom) -> Effect[None, Never, Scope]Keep atom mounted until the current scope closes.
| Parameter | Type | Description |
|---|---|---|
self | AtomRegistryService | |
atom | Atom[Any] |
Returns Effect[None, Never, Scope]
def mount(self: AtomRegistryService, atom: Atom[Any]) -> Effect[None, Never, Scope]:
"""Keep ``atom`` mounted until the current scope closes."""
return acquire_release(_Sync(lambda: self.mount(atom)), lambda release, _: _Sync(release)).as_(
None
)consume_skip_initial_run#
consume_skip_initial_run(ctx) -> boolWhether this build keeps the node's seeded value instead of running
its effect (an initial_value with skip_initial_run): once per
seed, and only while the parents it was seeded under are unchanged.
| Parameter | Type | Description |
|---|---|---|
ctx | AtomContext |
Returns bool
def consume_skip_initial_run(ctx: AtomContext) -> bool:
"""Whether this build keeps the node's seeded value instead of running
its effect (an ``initial_value`` with ``skip_initial_run``): once per
seed, and only while the parents it was seeded under are unchanged."""
from pyfect.reactivity.atom_registry._lifetime import Lifetime
lifetime = cast("Lifetime[Any]", ctx)
node = lifetime.node
if not node.skip_initial_run:
return False
kept = node.kept_parents
node.skip_initial_run = False
node.kept_parents = None
return (
not lifetime.is_fn
and not isinstance(node._value, Initial)
and (kept is None or all(parent.lifetime is life for parent, life in kept))
)batch#
batch(f) -> NoneRun f; dependents of what it changes are rebuilt, and listeners
told, once it returns (also when it raises: what it changed is kept).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[], None] |
def batch(f: Callable[[], None]) -> None:
"""Run ``f``; dependents of what it changes are rebuilt, and listeners
told, once it returns (also when it raises: what it changed is kept)."""
previous = state.phase
state.phase = COLLECT
state.depth += 1
failure: BaseException | None = None
try:
f()
except Exception as error:
failure = error
try:
if state.depth == 1:
stale, notify = state.stale, state.notify
i = 0
while True:
state.phase = COLLECT
while i < len(stale):
try:
stale[i].batch_rebuild()
except Exception as error:
failure = failure or error
i += 1
state.phase = COMMIT
while notify:
node = next(iter(notify))
try:
node.notify()
except Exception as error:
failure = failure or error
notify.pop(node, None)
if i >= len(stale):
break
state.stale = []
notify.clear()
finally:
state.depth -= 1
state.phase = previous
if failure is not None:
raise failure