Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Add an option to allow self-loops on `mo.state` (#809)

Akshay Agrawal81d9b08ddb4e
diff --git a/docs/guides/state.md b/docs/guides/state.md
index afb145f877..4c92f7e4f6 100644
--- a/docs/guides/state.md
+++ b/docs/guides/state.md
@@ -141,7 +141,9 @@ This rule has some important aspects:
1. Only cells that read the state getter via a global variable will be run.
2. The cell that called the setter won't be re-run, even if it references
- the getter.
+ the getter. This restriction helps prevent against bugs that could
+ otherwise arise. To lift this restriction, and allow the caller cell
+ to be re-run, create your state with `mo.state(value, allow_self_loops=True)`.
Notice how similar this rule is to the reactivity rule for UI element
interactions.
diff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.py
index afd87b0243..fc11d85666 100644
--- a/marimo/_runtime/cell_runner.py
+++ b/marimo/_runtime/cell_runner.py
@@ -166,7 +166,8 @@ class Runner:
1. The runner was not interrupted.
2. It was not already run after its setter was called.
- 3. It isn't the cell that called the setter.
+ 3. It isn't the cell that called the setter (unless the state
+ object was configured to allow self loops).
4. It is not errored (unable to run) or cancelled.
5. It has among its refs the state object whose setter
was invoked.
@@ -194,7 +195,7 @@ class Runner:
if self._runs_after(source=cid, target=setter_cell_id):
continue
# No self-loops (3)
- if cid == setter_cell_id:
+ if cid == setter_cell_id and not state.allow_self_loops:
continue
# No errorred/cancelled cells (4)
if cid in errored_cells or self.cancelled(cid):
diff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.py
index 2f7277ca0d..8c7caf7f9c 100644
--- a/marimo/_runtime/state.py
+++ b/marimo/_runtime/state.py
@@ -13,8 +13,9 @@ T = TypeVar("T")
class State(Generic[T]):
"""Mutable reactive state"""
- def __init__(self, value: T) -> None:
+ def __init__(self, value: T, allow_self_loops: bool = False) -> None:
self._value = value
+ self.allow_self_loops = allow_self_loops
def __call__(self) -> T:
return self._value
@@ -36,7 +37,9 @@ class State(Generic[T]):
@mddoc
-def state(value: T) -> tuple[State[T], Callable[[T], None]]:
+def state(
+ value: T, allow_self_loops: bool = False
+) -> tuple[State[T], Callable[[T], None]]:
"""Mutable reactive state
This function takes an initial value and returns:
@@ -45,8 +48,11 @@ def state(value: T) -> tuple[State[T], Callable[[T], None]]:
- a setter function to set the state's value
When you call the setter function and update the state value in one cell,
- all other cells that read any global variables assigned to the getter
- will automatically run.
+ all *other* cells that read any global variables assigned to the getter
+ will automatically run. By default, the cell that called the setter
+ function won't be re-run, even if it references the getter; to allow a
+ state setter to possibly run the caller cell, use the keyword argument
+ `allow_self_loops=True`.
You can use this function in conjunction with `UIElement` `on_change`
handlers to trigger side-effects when an element's value is updated. For
@@ -110,6 +116,11 @@ def state(value: T) -> tuple[State[T], Callable[[T], None]]:
**Args**:
- `value`: initial value of the state
+ - `allow_self_loops`: if True, if a cell calls a state setter
+ and also references its getter, the caller cell will be re-run;
+ defaults to `False`.
+
+
**Returns**:
@@ -117,5 +128,5 @@ def state(value: T) -> tuple[State[T], Callable[[T], None]]:
- setter function that takes a new value, or a function taking the current
value as its argument and returning a new value
"""
- state_instance = State(value)
+ state_instance = State(value, allow_self_loops=allow_self_loops)
return state_instance, state_instance._set_value
diff --git a/tests/_runtime/test_state.py b/tests/_runtime/test_state.py
index aece1107aa..75a4dac46e 100644
--- a/tests/_runtime/test_state.py
+++ b/tests/_runtime/test_state.py
@@ -53,6 +53,26 @@ def test_no_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:
assert k.globals["x"] == 0
+def test_allow_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get(
+ "state, set_state = mo.state(0, allow_self_loops=True)"
+ ),
+ exec_req.get(
+ """
+ x = state()
+ if x < 3:
+ set_state(x + 1)
+ """
+ ),
+ ]
+ )
+
+ assert k.globals["x"] == 3
+
+
def test_update_with_function(k: Kernel, exec_req: ExecReqProvider) -> None:
k.run(
[