Signals¶
Verification scope
The examples and semantics on this page were checked against hmr 0.7.6.3 and the current core source. This is a source and runtime check, not a claim of human review.
Observable values with automatic dependency tracking. Signals are the foundation of reactive programming, evolving from the observer pattern where data sources notify observers of changes.
The traditional observer pattern requires manual binding of subject and observer dependencies. Reactive programming implements automatic tracking of these dependencies on top of that.
A useful mental model is the call stack: if A calls B, then A depends on B. HMR starts from that intuition, but the real implementation is a little broader.
In synchronous code, dependency tracking often looks like "who is currently on the stack". In asynchronous code, HMR keeps that tracking alive through its reactivity context, so dependencies can still be collected across
awaitboundaries.
from reactivity import signal, state
signal creates standalone observables. state is a descriptor for class attributes.
Usage¶
In HMR, there are two primitives: Signal and Effect. Signal is like a data source:
from reactivity import signal
s = signal(0) # initial value is 0
print(s.get()) # use .get() to get the value of a signal
s.set(1) # set its value to 1
print(s.get())
s.update(lambda x: x + 1) # update using a function
This will print out 0 and then 1. As you can see, Signal is just a data source that tracks changes.
State descriptor¶
For class attributes, you can use the state descriptor:
class Counter:
value = state(0)
c = Counter()
c.value = 1 # notifies effects reading c.value
Each instance gets its own signal. Reading Counter.value on the class returns the descriptor, not an instance's value. Prefer immutable defaults; state does not copy a mutable initial value for each instance.
Equality and mutation¶
By default, setting an equal value does not notify subscribers. set() and update() return True when they notify, and False when the equality check suppresses the update. Use signal(value, check_equality=False) when every assignment should notify.
A signal observes assignments, not mutations inside its value. For example, appending to a list returned by s.get() does not notify. Create a new value with s.update(lambda items: [*items, new_item]), or use a reactive collection. Setting the same mutated object back is also suppressed by the default identity/equality check.
Tips¶
get(track=False)reads without subscribing to changesupdate(updater)modifies the signal using a functionbatch()groups updates to reduce recomputations- Use
statefor instance attributes,signalfor standalone values - Signals automatically track dependencies in the current reactive execution context, eliminating manual observer binding
See Also¶
- Effects for side effects that react to signals
- Derived for computed values based on signals
- Advanced Reactivity for patterns and best practices