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.

feat: state API (#42)

Akshay Agrawal3cdcc4365977
diff --git a/docs/_static/css/custom.css b/docs/_static/css/custom.css
index 400c7a098d..798de3aa5d 100644
--- a/docs/_static/css/custom.css
+++ b/docs/_static/css/custom.css
@@ -70,7 +70,7 @@ figcaption {
}
figure img {
- border: 1px solid #bbbbbb;
+ border: 1px solid #ebebeb;
border-radius: 5px;
}
diff --git a/docs/_static/docs-state-counter.gif b/docs/_static/docs-state-counter.gif
new file mode 100644
index 0000000000..33809ded97
Binary files /dev/null and b/docs/_static/docs-state-counter.gif differ
diff --git a/docs/_static/docs-state-task-list.gif b/docs/_static/docs-state-task-list.gif
new file mode 100644
index 0000000000..d0f0ab1b2e
Binary files /dev/null and b/docs/_static/docs-state-task-list.gif differ
diff --git a/docs/_static/docs-state-tied.gif b/docs/_static/docs-state-tied.gif
new file mode 100644
index 0000000000..d29efe0254
Binary files /dev/null and b/docs/_static/docs-state-tied.gif differ
diff --git a/docs/_static/docs-state-update.gif b/docs/_static/docs-state-update.gif
new file mode 100644
index 0000000000..e2badd31d5
Binary files /dev/null and b/docs/_static/docs-state-update.gif differ
diff --git a/docs/api/index.md b/docs/api/index.md
index 04594ebe52..b215bcbe67 100644
--- a/docs/api/index.md
+++ b/docs/api/index.md
@@ -10,6 +10,7 @@
layouts/index
media/index
html
+ state
misc
```
@@ -26,4 +27,5 @@ markdown and tabs.
| {doc}`layouts/index` | Customize outputs with accordions, tabs, stacks, and more |
| {doc}`media/index` | Output media like images and audio |
| {doc}`html` | Working with HTML objects |
+| {doc}`state` | Using reactive state |
| {doc}`misc` | Miscellaneous utilities |
diff --git a/docs/api/state.md b/docs/api/state.md
new file mode 100644
index 0000000000..b95dfca7e1
--- /dev/null
+++ b/docs/api/state.md
@@ -0,0 +1,5 @@
+# State
+
+```{eval-rst}
+.. autofunction:: marimo.state
+```
diff --git a/docs/guides/apps.md b/docs/guides/apps.md
index a0ab52dc43..b744c328d7 100644
--- a/docs/guides/apps.md
+++ b/docs/guides/apps.md
@@ -1,4 +1,4 @@
-# Apps
+# Run as an app
The marimo CLI lets you run any notebook as an app: `marimo run` hides the
notebook's code and starts a web server that hosts the resulting app.
diff --git a/docs/guides/best_practices.md b/docs/guides/best_practices.md
index 2fb7333b69..2f4cf1e774 100644
--- a/docs/guides/best_practices.md
+++ b/docs/guides/best_practices.md
@@ -1,4 +1,4 @@
-# Best Practices
+# Best practices
The few constraints marimo puts on your notebooks are natural consequences of
the fact that marimo programs are directed acyclic graphs. As long as you keep
diff --git a/docs/guides/index.md b/docs/guides/index.md
index 4d667d1708..12a2414aca 100644
--- a/docs/guides/index.md
+++ b/docs/guides/index.md
@@ -9,6 +9,7 @@
reactivity
interactivity
outputs
+ state
apps
scripts
best_practices
@@ -22,11 +23,12 @@ These guides cover marimo's core concepts.
| {doc}`reactivity` | How reactive execution works |
| {doc}`interactivity` | Using interactive UI elements |
| {doc}`outputs` | Markdown, plots, and other visual outputs |
+| {doc}`state` | Reacting to interactions with state |
| {doc}`apps` | Running notebooks as apps |
| {doc}`scripts` | Running notebooks as scripts |
| {doc}`best_practices` | Best practices when working with marimo |
-```{admonition} Learn by doing
+```{admonition} Learn by doing!
:class: tip
Prefer a hands-on learning experience? marimo comes packaged with interactive
diff --git a/docs/guides/scripts.md b/docs/guides/scripts.md
index 4329324ac5..4f5b633ee4 100644
--- a/docs/guides/scripts.md
+++ b/docs/guides/scripts.md
@@ -1,4 +1,4 @@
-# Scripts
+# Run as a script
You can run marimo notebooks as scripts at the command line, just like
any other Python script. For example,
diff --git a/docs/guides/state.md b/docs/guides/state.md
new file mode 100644
index 0000000000..7bac3380c4
--- /dev/null
+++ b/docs/guides/state.md
@@ -0,0 +1,317 @@
+# State
+
+```{admonition} Advanced topic!
+:class: warning
+
+This guide covers reactive state, an advanced topic. You likely don't need
+state for day-to-day exploratory data analysis or numerical experiments. We
+recommend skipping this guide and only returning here if you feel limited in
+your options to responding to user interactions.
+```
+
+You can build powerful, interactive notebooks and apps using just `mo.ui` and
+reactivity.
+
+But sometimes, you might want interactions to mutate state:
+
+- You're building a checklist, and you want to maintain a list of action
+ items, even as you add and remove some items.
+
+<div align="center" style="margin-top:2rem; margin-bottom:2rem">
+<figure>
+<img src="/_static/docs-state-task-list.gif"/>
+</figure>
+<figcaption>A proof-of-concept TODO list made using state.</figcaption>
+</div>
+
+
+- You want to tie two different UI elements so that updating one updates
+ the other.
+
+<div align="center" style="margin-top:2rem; margin-bottom:2rem">
+<figure>
+<img src="/_static/docs-state-tied.gif"/>
+<figcaption>Use state to tie two elements together.</figcaption>
+</figure>
+</div>
+
+
+For cases like these, marimo provides the function [`mo.state()`](/api/state),
+which creates a state object and returns a getter and setter function. When you
+call the setter function in one cell, all other cells that reference the getter
+function **via a global variable** are automatically run (similar to UI
+elements).
+
+
+```{admonition} State and UI elements are similar
+:class: note
+
+State is analogous to UI elements. When you interact
+with a UI element, all cells that reference that element via a global variable
+run automatically with the new value. In the same way, when you update state
+via the setter, all other cells that reference the getter via
+a global variable run automatically with the new value.
+
+State is particularly useful when used in conjunction with a `UIElement`'s
+`on_change` callback to run side effects based on user input.
+```
+
+## Creating state
+
+[`mo.state()`](/api/state) takes an initial state value as its argument, creates
+a state object, and returns
+
+- a getter function for reading the state
+- a setter function for updating the state
+
+For exaxmple,
+
+```python
+get_counter, set_counter = mo.state(0)
+```
+
+```{admonition} Assign state to global variables!
+:class: attention
+
+When using `mo.state()`, **you must assign the state getter to a global
+variable**. This is similar to UI elements work.
+```
+
+## Reading state
+
+Access the state's latest value via the getter:
+
+```python
+get_counter()
+```
+
+## Updating state
+
+You can update a state's value by calling its setter function with a new value.
+For example,
+
+```python
+set_counter(1)
+```
+
+To update the state based on its current value, pass a function that takes
+the current state value as an argument and returns a new value
+
+```python
+set_counter(lambda count: count + 1)
+```
+
+A single rule determines what happens next:
+
+```{admonition} State reactivity rule
+:class: tip
+
+When a state setter function is called in one cell, marimo
+automatically runs all _other_ cells that reference any **global** variables
+assigned to the state getter.
+```
+
+<div align="center" style="margin-bottom: 2rem; margin-top:2rem">
+<figure>
+<img src="/_static/docs-state-update.gif"/>
+</figure>
+<figcaption>Calling `set_counter` in the second cell triggers the third cell (which refs `get_counter`) to run.</figcaption>
+</div>
+
+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.
+
+Notice how similar this rule is to the reactivity rule for UI element
+interactions.
+
+## Using state with UI elements
+
+Every UI element takes an optional `on_change` callback, a function that takes
+the new value of the element and does anything with it. You can use the setter
+function in an `on_change` callback to mutate state.
+
+```{admonition} Use state sparingly
+:class: note
+
+You can get far using just `mo.ui`, without state. But judiciously using
+state can simplify the implementation of highly interactive notebooks/apps, and
+also enables new use cases. The next few examples showcase good uses of state.
+```
+
+### Example: counter
+The next few cells implement a counter controlled by two buttons. This
+particular example could be implemented without state (try it!), but the
+implementation using state is simpler.
+
+
+<div align="center">
+<figure>
+<img src="/_static/docs-state-counter.gif"/>
+</figure>
+</div>
+
+
+```python
+import marimo as mo
+```
+
+```python
+get_counter, set_counter = mo.state(0)
+
+increment = mo.ui.button(
+ label="increment",
+ on_change=lambda _: set_counter(lambda v: v + 1),
+)
+
+decrement = mo.ui.button(
+ label="decrement",
+ on_change=lambda _: set_counter(lambda v: v - 1),
+)
+
+mo.hstack([increment, decrement], justify="center")
+```
+
+```python
+mo.md(
+ f"""
+ The counter's current value is **{counter.value}**!
+
+ This cell runs automatically on button click, even though it
+ doesn't reference either button.
+ """
+)
+```
+
+### Example: tied elements
+
+This example shows how to tie two different UI elements so that each one's
+value depends on the other. This is impossible to do without `mo.state`.
+
+<div align="center">
+<figure>
+<img src="/_static/docs-state-tied.gif"/>
+</figure>
+</div>
+
+
+```python
+import marimo as mo
+```
+
+```python
+get_x, set_x = mo.state(0)
+```
+
+```python
+x = mo.ui.slider(
+ 0, 10, value=get_x(), on_change=set_x, label="$x$:"
+)
+```
+
+```python
+x_plus_one = mo.ui.number(
+ 1,
+ 11,
+ value=get_x() + 1,
+ on_change=lambda v: set_x_state(v - 1),
+ label="$x + 1$:",
+)
+```
+
+```python
+[x, x_plus_one]
+```
+
+```{admonition} Create tied UI elements in separate cells
+:class: note
+
+Notice that we created the slider and number elements in different cells.
+When tying elements, this is necessary, because calling a setter
+in a cell queues all _other_ cells reading the state to run, not including
+the one that just called the setter.
+```
+
+```{admonition} Cycles at runtime
+:class: warning
+You can use state to introduce cycles across cells at runtime. This lets
+you tie multiple UI elements together, for example. Just be careful not to
+introduce an infinite loop!
+
+marimo programs are statically parsed into directed acyclic graphs (DAGs)
+involving cells, and state doesn't change that. Think of state setters
+as hooking into the DAG: at runtime, when they're invoked (and only when
+they're invoked), they trigger additional computation.
+```
+
+### Example: todo list
+
+The next few cells use state to create a todo list.
+
+<div align="center">
+<figure>
+<img src="/_static/docs-state-task-list.gif"/>
+</figure>
+</div>
+
+
+```python
+import marimo as mo
+from dataclasses import dataclass
+```
+
+```python
+@dataclass
+class Task:
+ name: str
+ done: bool = False
+
+
+get_tasks, set_tasks = mo.state([])
+task_added, set_task_added = mo.state(False)
+```
+
+```python
+# Refresh the text box whenever a task is added
+task_added
+
+task_entry_box = mo.ui.text(placeholder="a task ...")
+```
+
+```python
+def add_task():
+ if task_entry_box.value:
+ set_tasks(lambda v: v + [Task(task_entry_box.value)])
+ set_task_added(True)
+
+def clear_tasks():
+ set_tasks(lambda v: [task for task in v if not task.done])
+
+add_task_button = mo.ui.button(
+ label="add task",
+ on_change=lambda _: add_task(),
+)
+
+clear_tasks_button = mo.ui.button(
+ label="clear completed tasks",
+ on_change=lambda _: clear_tasks()
+)
+```
+
+```
+task_list = mo.ui.array(
+ [mo.ui.checkbox(value=task.done, label=task.name) for task in get_tasks()],
+ label="tasks",
+ on_change=lambda v: set_tasks(
+ lambda tasks: [Task(task.name, done=v[i]) for i, task in enumerate(tasks)]
+ ),
+)
+```
+
+```
+mo.hstack(
+ [task_entry_box, add_task_button, clear_tasks_button], justify="start"
+)
+```
diff --git a/examples/ai/data_labeler.py b/examples/ai/data_labeler.py
index f8a43bf969..9ab9e7d67b 100644
--- a/examples/ai/data_labeler.py
+++ b/examples/ai/data_labeler.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.1.2"
+__generated_with = "0.1.4"
app = marimo.App()
@@ -12,12 +12,54 @@ def __(mo):
@app.cell
def __(NUMBER_OF_EXAMPLES, mo):
- index = mo.ui.number(0, NUMBER_OF_EXAMPLES, step=1)
+ get_index, set_index = mo.state(0)
- mo.md(f"**Choose an example to label.** {index}")
+
+ def increment_index():
+ set_index(lambda v: min(v + 1, NUMBER_OF_EXAMPLES - 1))
+
+
+ def decrement_index() -> int:
+ set_index(lambda v: max(0, v - 1))
+ return decrement_index, get_index, increment_index, set_index
+
+
+def __(decrement_index, increment_index, mo):
+ next_button = mo.ui.button(label="next", on_change=lambda _: increment_index())
+
+ previous_button = mo.ui.button(
+ label="previous", on_change=lambda _: decrement_index()
+ )
+ return next_button, previous_button
+
+
+def __(mo):
+ mo.md(f"**Choose an example to label.**")
+ return
+
+
+def __(NUMBER_OF_EXAMPLES, get_index, mo, set_index):
+ index = mo.ui.number(
+ 0,
+ NUMBER_OF_EXAMPLES - 1,
+ value=get_index(),
+ step=1,
+ debounce=True,
+ label="example number",
+ on_change=set_index,
+ )
return index,
+def __(index, mo, next_button, previous_button):
+ mo.hstack([index, previous_button, next_button], justify="start")
+ return
+
+
@app.cell
def __(index, mo):
mo.md(f"![img](https://picsum.photos/id/{index.value}/700/400)").center()
@@ -31,34 +73,62 @@ def __(mo):
@app.cell
-def __(index, labels, mo):
+def __(LABELS_PATH, NUMBER_OF_EXAMPLES, load_labels):
+ labels = load_labels(LABELS_PATH, NUMBER_OF_EXAMPLES)
+ return labels,
+
+
+def __(LABELS_PATH, labels, write_labels):
+ def update_label(value, index):
+ labels[index]["label"] = value
+ write_labels(labels, LABELS_PATH)
+ return update_label,
+
+
+def __(LABELS_PATH, labels, write_labels):
+ def update_notes(value, index):
+ labels[index]["notes"] = value
+ write_labels(labels, LABELS_PATH)
+ return update_notes,
+
+
+def __(mo, notes):
+ mo.stop(len(notes.value) <= 100)
+
+ _character_count = mo.md(f"`{len(notes.value)}/100` characters used").right()
+
+ mo.md(
+ f"""
+ Notes can't be longer than 100 characters. {_character_count}
+ """
+ ).callout(kind="alert")
+ return
+
+
+def __(index, labels, mo, update_label, update_notes):
data = labels[index.value]
label_picker = mo.ui.radio(
["Real", "AI Generated", "Unlabeled"],
value=data["label"],
label="**Selection.**",
+ on_change=lambda v: update_label(v, index.value),
)
- notes = mo.ui.text_area(value=data["notes"], label="**Notes.**")
+ notes = mo.ui.text_area(
+ value=data["notes"],
+ label="**Notes.**",
+ on_change=lambda v: update_notes(v, index.value),
+ )
mo.hstack([label_picker, notes], justify="space-around")
return data, label_picker, notes
-def __(LABELS_PATH, index, label_picker, labels, notes, write_labels):
- labels[index.value] = {"label": label_picker.value, "notes": notes.value}
- write_labels(labels, LABELS_PATH)
- return
-
-
-def __(LABELS_PATH, NUMBER_OF_EXAMPLES, load_labels):
- labels = load_labels(LABELS_PATH, NUMBER_OF_EXAMPLES)
- return labels,
-
-
@app.cell
def __(json, os):
def load_labels(path, number_of_examples):
@@ -75,6 +145,11 @@ def __(json, os):
def write_labels(labels, path):
+ # Trunacate notes
+ labels = [
+ {"label": item["label"], "notes": item["notes"][:100]}
+ for item in labels
+ ]
with open(path, "w") as f:
f.write(json.dumps(labels))
return load_labels, write_labels
diff --git a/examples/optimization/signals/app.py b/examples/optimization/signals/app.py
index a6068eb948..c9bc7f464a 100644
--- a/examples/optimization/signals/app.py
+++ b/examples/optimization/signals/app.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.1.0"
+__generated_with = "0.1.4"
app = marimo.App()
@@ -46,20 +46,32 @@ def __(complib, mo):
]
# will be used to track which options the user has tried
- component_radio_tracker = set()
+ get_component_radio_tracker, set_component_radio_tracker = mo.state(set())
- component_radio = mo.ui.radio(component_options, label="**Component Class**")
+ component_radio = mo.ui.radio(
+ component_options,
+ label="**Component Class**",
+ on_change=lambda w: set_component_radio_tracker(lambda v: v.union({w})),
+ )
other_component_radio = mo.ui.radio(
component_options, label="**Component Class**"
)
return (
component_options,
component_radio,
- component_radio_tracker,
+ get_component_radio_tracker,
other_component_radio,
+ set_component_radio_tracker,
)
+def __(component_options, get_component_radio_tracker):
+ def user_tried_all_components():
+ return len(get_component_radio_tracker()) == len(component_options)
+ return user_tried_all_components,
+
+
@app.cell
def __(component_radio, other_component_radio):
radios = [component_radio, other_component_radio]
@@ -83,9 +95,9 @@ def __(intro_problem, mo):
@app.cell
-def __(mo, show_third_component):
- _n_components = "2" if not show_third_component else "3"
- _three_component_text = " and third " if show_third_component else ""
+def __(get_show_third_component, mo):
+ _n_components = "2" if not get_show_third_component() else "3"
+ _three_component_text = " and third " if get_show_third_component() else ""
mo.md(
f"""
@@ -110,7 +122,7 @@ def __(mo, show_third_component):
@app.cell
-def __(intro, mo, radios, show_third_component):
+def __(get_show_third_component, intro, mo, radios):
# Show radios
(
mo.hstack(
@@ -124,29 +136,18 @@ def __(intro, mo, radios, show_third_component):
),
],
)
- if not show_third_component
+ if not get_show_third_component()
else mo.hstack(radios, justify="space-around")
)
return
@app.cell
-def __(component_options, component_radio_tracker, radios):
- if radios[0].value is not None:
- component_radio_tracker.add(radios[0].value)
-
-
- def user_tried_all_components():
- return len(component_radio_tracker) == len(component_options)
- return user_tried_all_components,
-
-
-def __(intro, mo, radios, show_third_component):
+def __(get_show_third_component, intro, mo, radios):
# Plot 3-component decomposition
(
None
- if not show_third_component
+ if not get_show_third_component()
else mo.hstack(
[
*intro.plot_decomp(
@@ -162,11 +163,11 @@ def __(intro, mo, radios, show_third_component):
@app.cell
-def __(explainer, mo, radios, show_third_component):
+def __(explainer, get_show_third_component, mo, radios):
# Component explainer callout
(
mo.md(explainer.explainer(radios[0].value)).callout(kind="neutral")
- if not show_third_component and radios[0].value is not None
+ if not get_show_third_component() and radios[0].value is not None
else None
)
return
@@ -174,36 +175,29 @@ def __(explainer, mo, radios, show_third_component):
@app.cell
def __(mo):
- class _Toggle:
- value = False
-
- def toggle(self):
- self.value = not self.value
- return self
-
- def __bool__(self):
- return self.value
-
+ get_show_third_component, set_show_third_component = mo.state(False)
- _show_third_component = _Toggle()
add_component_button = mo.ui.button(
label="Add another component 🔧",
- value=_show_third_component,
- on_click=lambda v: v.toggle(),
+ on_change=lambda _: set_show_third_component(True),
)
remove_component_button = mo.ui.button(
label="Remove third component 🔧",
- value=_show_third_component,
- on_click=lambda v: v.toggle(),
+ on_change=lambda _: set_show_third_component(False),
+ )
+ return (
+ add_component_button,
+ get_show_third_component,
+ remove_component_button,
+ set_show_third_component,
)
- return add_component_button, remove_component_button
@app.cell
def __(
add_component_button,
+ get_show_third_component,
mo,
- show_third_component,
solved,
user_tried_all_components,
):
@@ -218,9 +212,9 @@ def __(
small and random. _When that happens, that usually means we
need to add another component to our decomposition_.
"""
- ).callout(kind="alert")
+ ).callout(kind="warn")
if user_tried_all_components()
- and not show_third_component
+ and not get_show_third_component()
and not solved.now
else None
)
@@ -265,7 +259,7 @@ def __(complib, radios, solved_ever):
@app.cell
-def __(mo, show_third_component, solved):
+def __(get_show_third_component, mo, solved):
# Solved callout
(
mo.md(
@@ -289,7 +283,7 @@ def __(mo, show_third_component, solved):
**Part 2 is now available**.
"""
).callout(kind="success")
- if show_third_component and solved.now
+ if get_show_third_component() and solved.now
else None
)
return
@@ -309,7 +303,7 @@ def __(mo, solved):
ever unsure about what a component does, check out the reference
at the bottom of the page.
"""
- ).callout(kind="alert")
+ ).callout(kind="warn")
if solved.ever
else None
)
@@ -318,9 +312,9 @@ def __(mo, solved):
@app.cell
def __(
+ get_show_third_component,
mo,
remove_component_button,
- show_third_component,
solved,
user_tried_all_components,
):
@@ -336,22 +330,15 @@ def __(
Hint: we generated the signal by adding a seasonal fluctuation
to a line with constant slope.
"""
- ).callout(kind="alert")
- if user_tried_all_components() and show_third_component and not solved.now
+ ).callout(kind="warn")
+ if user_tried_all_components()
+ and get_show_third_component()
+ and not solved.now
else None
)
return
-def __(add_component_button, remove_component_button):
- # Interacting with either button should update `show_third_component`
- (add_component_button, remove_component_button)
-
- show_third_component = add_component_button.value
- return show_third_component,
-
-
@app.cell
def __(mo):
mo.md("## Part 2: More Decompositions")
@@ -397,17 +384,11 @@ def __(mo, selected_problem, solved):
component classes in part 1 until you've "solved" the decomposition,
then return here.
"""
- ).callout(kind="warn")
+ ).callout(kind="alert")
)
return
-def __(problems, selected_problem):
- show_data_uploader = selected_problem.value == problems.CustomDataProblem
- return show_data_uploader,
-
-
@app.cell
def __(mo):
data_uploader = mo.ui.file(filetypes=[".csv"], kind="area")
@@ -416,7 +397,7 @@ def __(mo):
@app.cell
-def __(csv_has_header, data_uploader, mo, show_data_uploader):
+def __(csv_has_header, data_uploader, mo):
def read_uploaded_csv():
from io import BytesIO
import pandas as pd
@@ -435,7 +416,7 @@ def __(csv_has_header, data_uploader, mo, show_data_uploader):
)
- def _show_csv_parameters():
+ def show_csv_parameters():
if _uploaded_df is not None:
return f"""
@@ -449,31 +430,33 @@ def __(csv_has_header, data_uploader, mo, show_data_uploader):
"""
else:
return ""
+ return column_name, read_uploaded_csv, show_csv_parameters
- (
- mo.md(
- f"""
- **Upload a signal.**
+def __(data_uploader, mo, problems, selected_problem, show_csv_parameters):
+ mo.stop(selected_problem.value != problems.CustomDataProblem)
- You can upload your own signal and use this app to build a
- decomposition for it. Your signal should be a CSV file.
+ mo.md(
+ f"""
+ **Upload a signal.**
- {data_uploader}
+ You can upload your own signal and use this app to build a
+ decomposition for it. Your signal should be a CSV file.
- {_show_csv_parameters()}
- """
- ).callout()
- if show_data_uploader
- else None
- )
- return column_name, read_uploaded_csv
+ {data_uploader}
+
+ {show_csv_parameters()}
+ """
+ ).callout()
+ return
@app.cell
def __(
column_name,
data_uploader,
+ mo,
problems,
read_uploaded_csv,
selected_problem,
@@ -493,193 +476,136 @@ def __(
problem = _construct_problem(selected_problem.value)
- return problem,
-
-def __(mo, problem):
- mo.md(f"### {problem.name()}") if problem is not None else None
- return
+ # State associated with each problem
+ # The number of components in the decomposition
+ get_k, set_k = mo.state(2)
+ # The components selected: maintain as state so we can pre-populate
+ # them as components are added and removed
+ get_selected_components, set_selected_components = mo.state([])
+ (
+ get_selected_aggregate_components,
+ set_selected_aggregate_components,
+ ) = mo.state({})
-def __(problem):
- problem.description() if problem is not None else None
- return
+ # The parameters selected: maintain as state so we can pre-populate
+ get_selected_params, set_selected_params = mo.state({})
+ get_selected_aggregate_params, set_selected_aggregate_params = mo.state({})
+ return (
+ get_k,
+ get_selected_aggregate_components,
+ get_selected_aggregate_params,
+ get_selected_components,
+ get_selected_params,
+ problem,
+ set_k,
+ set_selected_aggregate_components,
+ set_selected_aggregate_params,
+ set_selected_components,
+ set_selected_params,
+ )
@app.cell
-def __(mo, problem):
- # Add a ref to `problem`:
- # When the problem is changed, this cell should be reset.
- problem
-
-
- class _Counter:
- def __init__(self, value):
- self.value = value
-
- def increment(self):
- self.value += 1
- return self
-
- def decrement(self):
- self.value = max(2, self.value - 1)
- return self
-
-
- part_two_n_components_counter = _Counter(2)
-
+def __(mo, set_k):
add_button = mo.ui.button(
- value=part_two_n_components_counter,
- on_click=lambda v: v.increment(),
+ on_change=lambda _: set_k(lambda v: v + 1),
label="Add a component",
)
+
remove_button = mo.ui.button(
- value=part_two_n_components_counter,
- on_click=lambda v: v.decrement(),
+ on_click=lambda _: set_k(lambda v: max(2, v - 1)),
label="Remove a component",
)
- return add_button, part_two_n_components_counter, remove_button
-
-
-def __(add_button, part_two_n_components_counter, remove_button):
- (add_button, remove_button)
-
- part_two_k = part_two_n_components_counter.value
- return part_two_k,
-
-
-def __(problem):
- # Add a ref to `problem`:
- # When the problem is changed, this cell should be reset.
- problem
-
- selected_components = []
- selected_params = {}
-
-
- def get_default_component_value(index):
- if index >= len(selected_components):
- return None
- return selected_components[index]
- return get_default_component_value, selected_components, selected_params
+ return add_button, remove_button
@app.cell
def __(
- component_array,
- component_params,
- selected_components,
- selected_params,
+ complib,
+ get_k,
+ get_selected_components,
+ mo,
+ set_selected_components,
):
- # When the component classes or their parameters change, we need to update
- # their default values
- selected_components[:] = component_array.value
-
- selected_params.clear()
- selected_params.update(component_params.value)
- return
+ def _get_default_component_value(index):
+ if index >= len(get_selected_components()):
+ return None
+ return get_selected_components()[index]
-def __(complib, get_default_component_value, mo, part_two_k):
_dropdowns = [
mo.ui.dropdown(
complib.RESIDUAL_COMPONENTS if i == 0 else complib.COMPONENT_LIBRARY,
- value=get_default_component_value(i),
+ value=_get_default_component_value(i),
allow_select_none=True,
)
- for i in range(part_two_k)
+ for i in range(get_k())
]
- component_array = mo.ui.array(_dropdowns, label="Components")
+ component_array = mo.ui.array(
+ _dropdowns, label="Components", on_change=set_selected_components
+ )
return component_array,
@app.cell
def __(
- add_button,
complib,
component_array,
+ get_selected_params,
mo,
- problem,
- remove_button,
- selected_params,
+ set_selected_params,
):
- # Add a ref to `problem`:
- # This cell shouldn't show when a problem isn't selected,
- # and when the problem is changed, this cell should be reset.
- problem
-
component_params = mo.ui.dictionary(
{
- f"{i}": complib.parameter_controls(c, selected_params.get(str(i), {}))
+ f"{i}": complib.parameter_controls(
+ c, get_selected_params().get(str(i), {})
+ )
for i, c in enumerate(component_array.value)
if c is not None
},
label="Parameters",
- )
-
- (
- mo.md(
- f"""
- ## {mo.md(f"{add_button} {remove_button}").center()}
- """
- )
- if problem is not None
- else None
+ on_change=set_selected_params,
)
return component_params,
@app.cell
-def __(component_array, component_params, mo, problem):
- (
- mo.hstack([component_array, component_params])
- if problem is not None
- else None
- )
+def __(mo, problem):
+ mo.stop(problem is None)
+
+ mo.md(f"### {problem.name()}")
return
@app.cell
-def __(component_array):
- noise_component_selected = component_array.value[0] is not None
- return noise_component_selected,
-
+def __(mo, problem):
+ mo.stop(problem is None)
-def __(component_array, noise_component_selected, problem):
- should_compute_decomposition = (
- noise_component_selected
- and sum(1 for v in component_array.value if v is not None) >= 2
- ) and problem is not None
- return should_compute_decomposition,
+ problem.description()
+ return
@app.cell
-def __(problem):
- problem
+def __(add_button, mo, problem, remove_button):
+ mo.stop(problem is None)
- selected_aggregate_components = {}
- selected_aggregate_params = {}
+ mo.md(
+ f"""
+ ## {mo.md(f"{add_button} {remove_button}").center()}
+ """
+ )
+ return
- def get_default_aggregate_component_value(key, index):
- if key not in selected_aggregate_components:
- return None
- selected_components = selected_aggregate_components[key]
- if index >= len(selected_components):
- return None
- return selected_components[index]
- return (
- get_default_aggregate_component_value,
- selected_aggregate_components,
- selected_aggregate_params,
- )
+def __(component_array, component_params, mo, problem):
+ mo.stop(problem is None)
+
+ mo.hstack([component_array, component_params])
+ return
@app.cell
@@ -687,52 +613,56 @@ def __(
complib,
component_array,
component_params,
- get_default_aggregate_component_value,
+ get_selected_aggregate_components,
mo,
+ set_selected_aggregate_components,
):
_aggregates = {}
_options = [v for v in complib.COMPONENT_LIBRARY if v != "Aggregate"]
+
+ def _get_default_aggregate_component_value(key, index):
+ if key not in get_selected_aggregate_components():
+ return None
+ selected_components = get_selected_aggregate_components()[key]
+ if index >= len(selected_components):
+ return None
+ return selected_components[index]
+
+
for _i, _component in enumerate(component_array.value):
_key = str(_i)
if _component == "Aggregate":
_dropdowns = [
mo.ui.dropdown(
_options,
- get_default_aggregate_component_value(_key, i),
+ _get_default_aggregate_component_value(_key, i),
allow_select_none=True,
)
for i in range(component_params.value[_key]["components"])
]
_aggregates[_key] = mo.ui.array(_dropdowns, label="components")
- aggregates = mo.ui.dictionary(_aggregates, label="Aggregates")
+ aggregates = mo.ui.dictionary(
+ _aggregates,
+ label="Aggregates",
+ on_change=set_selected_aggregate_components,
+ )
return aggregates,
@app.cell
def __(
- aggregate_params,
aggregates,
- selected_aggregate_components,
- selected_aggregate_params,
+ complib,
+ get_selected_aggregate_params,
+ mo,
+ set_selected_aggregate_params,
):
- selected_aggregate_components.clear()
- selected_aggregate_components.update(aggregates.value)
-
- selected_aggregate_params.clear()
- selected_aggregate_params.update(aggregate_params.value)
- return
-
-
-def __(aggregates, complib, mo, problem, selected_aggregate_params):
- problem
-
_aggregate_params = {}
for _key, _components in aggregates.value.items():
- defaults = selected_aggregate_params.get(_key, {})
+ defaults = get_selected_aggregate_params().get(_key, {})
_aggregate_params[_key] = mo.ui.dictionary(
{
f"{i}": complib.parameter_controls(c, defaults.get(str(i), {}))
@@ -743,7 +673,9 @@ def __(aggregates, complib, mo, problem, selected_aggregate_params):
)
aggregate_params = mo.ui.dictionary(
- _aggregate_params, label="Aggregate Parameters"
+ _aggregate_params,
+ label="Aggregate Parameters",
+ on_change=set_selected_aggregate_params,
)
(mo.hstack([aggregates, aggregate_params]) if aggregates.value else None)
@@ -770,6 +702,21 @@ def __(aggregate_params, aggregates, component_params):
return rolled_up_params,
+def __(component_array):
+ noise_component_selected = component_array.value[0] is not None
+ return noise_component_selected,
+
+
+def __(component_array, noise_component_selected, problem):
+ should_compute_decomposition = (
+ noise_component_selected
+ and sum(1 for v in component_array.value if v is not None) >= 2
+ ) and problem is not None
+ return should_compute_decomposition,
+
+
@app.cell
def __(
component_array,
@@ -779,6 +726,8 @@ def __(
rolled_up_params,
should_compute_decomposition,
):
+ mo.stop(problem is None)
+
def _feedback():
if not noise_component_selected and any(
v is not None for v in component_array.value
@@ -801,8 +750,7 @@ def __(
rolled_up_params,
)
-
- _feedback() if problem is not None else None
+ _feedback()
return
@@ -836,11 +784,14 @@ def __(construct_components):
def __(
component_array,
decompose,
+ mo,
plt,
problem,
rolled_up_params,
should_compute_decomposition,
):
+ mo.stop(not should_compute_decomposition)
+
def _do_decomposition():
components = tuple([v for v in component_array.value if v is not None])
f = decompose(problem, components, rolled_up_params)
@@ -853,7 +804,7 @@ def __(
return f
- _do_decomposition() if should_compute_decomposition else None
+ _do_decomposition()
return
@@ -865,16 +816,14 @@ def __(complib, mo):
@app.cell
def __(explainer_choice, mo, solved):
- (
- mo.md(
- f"""
- ## Reference
+ mo.stop(not solved.ever)
- Tell me more about the {explainer_choice} component class.
- """
- )
- if solved.ever
- else None
+ mo.md(
+ f"""
+ ## Reference
+
+ Tell me more about the {explainer_choice} component class.
+ """
)
return
@@ -889,22 +838,20 @@ def __(explainer, explainer_choice, mo):
@app.cell
def __(mo, solved):
- (
- mo.md(
- """
- #### More about Signal Decomposition
+ mo.stop(not solved.ever)
+
+ mo.md(
+ """
+ #### More about Signal Decomposition
- This tutorial is based on the research book, ["Signal Decomposition
- Using Masked Proximal Operators"](https://web.stanford.edu/~boyd/papers/sig_decomp_mprox.html),
- by Bennet Meyers and Stephen Boyd. It uses the [`signal-decomp`](https://github.com/cvxgrp/signal-decomposition) Python library to
- compute decompositions.
+ This tutorial is based on the research book, ["Signal Decomposition
+ Using Masked Proximal Operators"](https://web.stanford.edu/~boyd/papers/sig_decomp_mprox.html),
+ by Bennet Meyers and Stephen Boyd. It uses the [`signal-decomp`](https://github.com/cvxgrp/signal-decomposition) Python library to
+ compute decompositions.
- We hope this app shows that math can be intuitive, actionable,
- and fun.
- """
- )
- if solved.ever
- else None
+ We hope this app shows that math can be intuitive, actionable,
+ and fun.
+ """
)
return
diff --git a/examples/optimization/signals/modules/dataloaders.py b/examples/optimization/signals/modules/dataloaders.py
index 5b8ec0e1db..3e127a5f48 100644
--- a/examples/optimization/signals/modules/dataloaders.py
+++ b/examples/optimization/signals/modules/dataloaders.py
@@ -9,15 +9,11 @@ import pandas as pd
def get_c02_data() -> pd.DataFrame:
- path = "../data/co2_weekly_mlo.csv"
- if not os.path.isfile(path):
- path = (
- "https://gml.noaa.gov/webdata/ccgg/trends/co2/co2_weekly_mlo.csv"
- )
+ path = "https://gml.noaa.gov/webdata/ccgg/trends/co2/co2_weekly_mlo.csv"
df = pd.read_csv(
path,
- # column names on row 52, data starts on row 53
- skiprows=51,
+ # column names on row 35, data starts on row 56
+ skiprows=34,
index_col=False,
na_values=[-999.99],
)
diff --git a/examples/optimization/signals/modules/problems.py b/examples/optimization/signals/modules/problems.py
index d8795e4f65..dfdf3e60da 100644
--- a/examples/optimization/signals/modules/problems.py
+++ b/examples/optimization/signals/modules/problems.py
@@ -439,8 +439,8 @@ class Soiling(OSDProblem):
return "Solar Panel Soiling"
def description(self):
- reference_decomposition = mo.Html(
- layout.image("assets/solar_power_soiling_reference.png")
+ reference_decomposition = layout.image(
+ "assets/solar_power_soiling_reference.png"
)
return mo.md(
f"""
@@ -463,7 +463,7 @@ class Soiling(OSDProblem):
We've created what we think is a good decomposition for this
data. Here it is:
- {mo.tree([reference_decomposition], label="Reference Decomposition")}
+ {mo.tree([reference_decomposition], label="reference decomposition")}
**Your task:** Create a decomposition that matches our reference
decomposition.
diff --git a/examples/task_list.py b/examples/task_list.py
index d1dfb4911d..cc365f2faf 100644
--- a/examples/task_list.py
+++ b/examples/task_list.py
@@ -1,101 +1,85 @@
import marimo
-__generated_with = "0.1.0"
+__generated_with = "0.1.4"
app = marimo.App()
@app.cell
def __(mo):
- mo.md("# Task List")
+ mo.md("# Task List").left()
return
@app.cell
-def __(add_task_button, clear_tasks_button, mo, state, task):
- # Construct the task list based on the task list state.
- #
- # This cell will re-run and reconstruct the task list with updated state
- # whenever either of the buttons are clicked, since they include references
- # to the button elements.
- task_list = mo.ui.array(
- [
- mo.ui.checkbox(value=v, label=l)
- for v, l in zip(state.values, state.labels)
- ],
- label="tasks",
- )
+def __(dataclass):
+ @dataclass
+ class Task:
+ name: str
+ done: bool = False
+ return Task,
- (
- task,
- add_task_button,
- clear_tasks_button,
- task_list if state.values else mo.md("No tasks! 🎉"),
- )
- return task_list,
+
+def __(mo):
+ get_tasks, set_tasks = mo.state([])
+ mutation_signal, set_mutation_signal = mo.state(False)
+ return get_tasks, mutation_signal, set_mutation_signal, set_tasks
@app.cell
-def __(state, task_list):
- # This cell runs whenever a task is checked or unchecked, updating the state.
- #
- # This makes use of the fact that writing to attributes (non-globals) doesn't
- # trigger reactive execution.
- #
- # In the future we may introduce an API for setting state.
- state.values[:] = task_list.value
- return
+def __(mo, mutation_signal):
+ mutation_signal
+
+ task_entry_box = mo.ui.text(placeholder="a task ...")
+ return task_entry_box,
@app.cell
-def __(mo):
- # A text input for entering a task
- task = mo.ui.text(placeholder="a task ...")
-
- class TaskListState:
- """
- This class holds the state of the task list: the tasks (labels),
- and whether they've been completed (values).
- """
- def __init__(self):
- # The task labels
- self.labels = []
- # Whether each label is checked
- self.values = []
-
- def add_task(self):
- if task.value:
- # Add the current value of the task input to `self.labels`
- self.labels.append(task.value)
- # The task starts as incomplete
- self.values.append(False)
- return self
-
- def clear_tasks(self):
- # Remove all completed tasks from state
- self.labels[:] = [
- label
- for i, label in enumerate(self.labels)
- if not self.values[i]
- ]
- self.values[:] = [v for v in self.values if not v]
- return self
-
- state = TaskListState()
-
- # Buttons to add and remove tasks; these buttons mutate state when they
- # are clicked.
+def __(Task, mo, set_mutation_signal, set_tasks, task_entry_box):
+ def add_task():
+ if task_entry_box.value:
+ set_tasks(lambda v: v + [Task(task_entry_box.value)])
+ set_mutation_signal(True)
+
+
add_task_button = mo.ui.button(
- value=state,
- on_click=lambda state: state.add_task(),
label="add task",
+ on_change=lambda _: add_task(),
)
clear_tasks_button = mo.ui.button(
- value=state,
- on_click=lambda state: state.clear_tasks(),
label="clear completed tasks",
+ on_change=lambda _: set_tasks(
+ lambda v: [task for task in v if not task.done]
+ ),
)
- return TaskListState, add_task_button, clear_tasks_button, state, task
+ return add_task, add_task_button, clear_tasks_button
+
+
+def __(add_task_button, clear_tasks_button, mo, task_entry_box):
+ mo.hstack(
+ [task_entry_box, add_task_button, clear_tasks_button], justify="start"
+ )
+ return
+
+
+def __(Task, get_tasks, mo, set_tasks):
+ task_list = mo.ui.array(
+ [mo.ui.checkbox(value=task.done, label=task.name) for task in get_tasks()],
+ label="tasks",
+ on_change=lambda v: set_tasks(
+ [Task(task.name, done=v[i]) for i, task in enumerate(get_tasks())]
+ ),
+ )
+ return task_list,
+
+
+def __(mo, task_list):
+ mo.as_html(task_list) if task_list.value else mo.md("No tasks! 🎉")
+ return
@app.cell
@@ -104,5 +88,11 @@ def __():
return mo,
+def __():
+ from dataclasses import dataclass
+ return dataclass,
+
+
if __name__ == "__main__":
app.run()
diff --git a/frontend/src/core/RuntimeState.ts b/frontend/src/core/RuntimeState.ts
index 7f83e8d238..305b3ecb7b 100644
--- a/frontend/src/core/RuntimeState.ts
+++ b/frontend/src/core/RuntimeState.ts
@@ -59,11 +59,12 @@ export class RuntimeState {
flushUpdates() {
if (this.componentsToUpdate.size > 0) {
this.registerRunStart();
+
sendComponentValues(
Array.from(this.componentsToUpdate.values(), (objectId) => ({
objectId: objectId,
value: this.uiElementRegistry.lookupValue(objectId),
- }))
+ })).filter((update) => update.value !== undefined)
);
this.componentsToUpdate.clear();
}
diff --git a/frontend/src/core/dom/uiregistry.ts b/frontend/src/core/dom/uiregistry.ts
index b97fec2c4d..670249e3cc 100644
--- a/frontend/src/core/dom/uiregistry.ts
+++ b/frontend/src/core/dom/uiregistry.ts
@@ -98,11 +98,11 @@ export class UIElementRegistry {
* Get the value of a registered UIElement.
*
* @param objectId - id of the UIElement
- * @returns the value for `objectId`, or `null` if the object was not found.
+ * @returns the value for `objectId`, or `undefined` if the object was not found.
*/
- lookupValue(objectId: string): ValueType | null {
+ lookupValue(objectId: string): ValueType | undefined {
const entry = this.entries.get(objectId);
- return entry === undefined ? null : entry.value;
+ return entry === undefined ? undefined : entry.value;
}
/**
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 6ac6e77e26..91125673f2 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -31,6 +31,7 @@ __all__ = [
"pdf",
"refs",
"right",
+ "state",
"stop",
"tabs",
"tree",
@@ -57,3 +58,4 @@ from marimo._plugins.stateless.tabs import tabs
from marimo._plugins.stateless.tree import tree
from marimo._runtime.control_flow import MarimoStopError, stop
from marimo._runtime.runtime import defs, refs
+from marimo._runtime.state import state
diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.py
index 3d055d5b0e..9df5a79fd7 100644
--- a/marimo/_plugins/ui/_core/registry.py
+++ b/marimo/_plugins/ui/_core/registry.py
@@ -29,8 +29,8 @@ class UIElementRegistry:
) -> None:
kernel = get_context().kernel
self._objects[object_id] = weakref.ref(ui_element)
- assert kernel.cell_id is not None
- self._constructing_cells[object_id] = kernel.cell_id
+ assert kernel.execution_context is not None
+ self._constructing_cells[object_id] = kernel.execution_context.cell_id
if object_id in self._bindings:
# If `register` is called on an object_id that is being
# reused before `delete` is called, bindings won't have been
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index 0c51cc958f..190dde3601 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import abc
import copy
import uuid
-from typing import TYPE_CHECKING, Generic, Optional, TypeVar, cast
+from typing import TYPE_CHECKING, Callable, Generic, Optional, TypeVar, cast
from marimo import _loggers
from marimo._output.hypertext import Html
@@ -63,6 +63,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
component_name: str,
initial_value: S,
label: Optional[str],
+ on_change: Optional[Callable[[T], None]],
args: dict[str, JSONType],
slotted_html: str = "",
) -> None:
@@ -75,9 +76,17 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
label: markdown string, label of element
args: arguments that the element takes
slotted_html: any html to slot in the custom element
+ on_change: callback, called with element's new value on change
"""
# arguments stored in signature order for cloning
- self._args = (component_name, initial_value, label, args, slotted_html)
+ self._args = (
+ component_name,
+ initial_value,
+ label,
+ on_change,
+ args,
+ slotted_html,
+ )
self._initialized = False
self._initialize(*self._args)
self._initialized = True
@@ -87,6 +96,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
component_name: str,
initial_value: S,
label: Optional[str],
+ on_change: Optional[Callable[[T], None]],
args: dict[str, JSONType],
slotted_html: str,
) -> None:
@@ -143,6 +153,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
pass
self._initial_value_frontend = initial_value
self._value = self._initial_value = self._convert_value(initial_value)
+ self._on_change = on_change
self._inner_text = build_ui_plugin(
component_name,
@@ -173,8 +184,12 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
ctx = get_context()
if (
ctx.initialized
- and ctx.kernel.cell_id
- == ctx.ui_element_registry.get_cell(self._id)
+ and ctx.kernel.execution_context is not None
+ and not ctx.kernel.execution_context.setting_element_value
+ and (
+ ctx.kernel.execution_context.cell_id
+ == ctx.ui_element_registry.get_cell(self._id)
+ )
):
raise RuntimeError(
"Accessing the value of a UIElement in the cell that created "
@@ -230,7 +245,14 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
return form_plugin(element=self, label=label)
def _update(self, value: S) -> None:
+ """Update value, given a value from the frontend
+
+ Calls the on_change handler with the element's new value as a
+ side-effect.
+ """
self._value = self._convert_value(value)
+ if self._on_change is not None:
+ self._on_change(self._value)
def __del__(self) -> None:
ctx = get_context()
diff --git a/marimo/_plugins/ui/_impl/array.py b/marimo/_plugins/ui/_impl/array.py
index 9450ebd7e6..db44ce97a6 100644
--- a/marimo/_plugins/ui/_impl/array.py
+++ b/marimo/_plugins/ui/_impl/array.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, Dict, Final, Sequence
+from typing import Any, Callable, Dict, Final, Optional, Sequence
from marimo._output.formatters.structures import format_structure
from marimo._output.rich_help import mddoc
@@ -55,6 +55,7 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):
- `elements`: the UI elements to include
- `label`: a descriptive name for the array
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-dict"
@@ -64,6 +65,7 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):
elements: Sequence[UIElement[Any, Any]],
*,
label: str = "",
+ on_change: Optional[Callable[[Sequence[object]], None]] = None,
) -> None:
self._elements = [e._clone() for e in elements]
self._label = label
@@ -84,6 +86,7 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):
},
},
slotted_html=slotted_html.text,
+ on_change=on_change,
)
@property
diff --git a/marimo/_plugins/ui/_impl/batch.py b/marimo/_plugins/ui/_impl/batch.py
index a4c9e325f6..636e0d538d 100644
--- a/marimo/_plugins/ui/_impl/batch.py
+++ b/marimo/_plugins/ui/_impl/batch.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, Dict, Final
+from typing import Any, Callable, Dict, Final, Optional
from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
@@ -23,6 +23,7 @@ class _batch_base(UIElement[Dict[str, JSONType], Dict[str, object]]):
html: Html,
elements: dict[str, UIElement[JSONType, object]],
label: str = "",
+ on_change: Optional[Callable[[Dict[str, object]], None]] = None,
) -> None:
self._elements = elements
super().__init__(
@@ -38,6 +39,7 @@ class _batch_base(UIElement[Dict[str, JSONType], Dict[str, object]]):
},
},
slotted_html=html.text,
+ on_change=on_change,
)
@property
@@ -96,23 +98,27 @@ class batch(_batch_base):
- `value`: a `dict` of the batched elements' values
- `elements`: a `dict` of the batched elements (clones of the originals)
+ - `on_change`: optional callback to run when this element's value changes
**Initialization Args.**
- html: a templated `Html` object
- elements: the UI elements to interpolate into the HTML template
+ - `on_change`: optional callback to run when this element's value changes
"""
def __init__(
self,
html: Html,
elements: dict[str, UIElement[Any, Any]],
+ on_change: Optional[Callable[[Dict[str, object]], None]] = None,
) -> None:
self._html = html
elements = {key: element._clone() for key, element in elements.items()}
super().__init__(
html=Html(self._html.text.format(**elements)),
elements=elements,
+ on_change=on_change,
)
def _clone(self) -> batch:
diff --git a/marimo/_plugins/ui/_impl/dictionary.py b/marimo/_plugins/ui/_impl/dictionary.py
index 5690392502..e5f26d107f 100644
--- a/marimo/_plugins/ui/_impl/dictionary.py
+++ b/marimo/_plugins/ui/_impl/dictionary.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any
+from typing import Any, Callable, Optional
from marimo._output.formatters.structures import format_structure
from marimo._output.rich_help import mddoc
@@ -55,6 +55,7 @@ class dictionary(_batch_base):
- `value`: a dict holding the values of the UI elements, keyed by
their names.
- `elements`: a dict of the wrapped elements (clones of the originals)
+ - `on_change`: optional callback to run when this element's value changes
**Initialization Args.**
@@ -68,6 +69,7 @@ class dictionary(_batch_base):
elements: dict[str, UIElement[Any, Any]],
*,
label: str = "",
+ on_change: Optional[Callable[[dict[str, object]], None]] = None,
) -> None:
# Why we clone the wrapped elements:
#
@@ -95,7 +97,12 @@ class dictionary(_batch_base):
json_data=format_structure(elements),
name="dictionary" if not label else label,
)
- super().__init__(html=slotted_html, elements=elements, label=label)
+ super().__init__(
+ html=slotted_html,
+ elements=elements,
+ label=label,
+ on_change=on_change,
+ )
def _clone(self) -> dictionary:
"""Custom clone method so new dict gets copies of UI elements."""
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index b581566724..337cdd6207 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -57,6 +57,7 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):
- `debounce`: whether to debounce (rate-limit) value
updates from the frontend
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-number"
@@ -70,6 +71,7 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):
debounce: bool = False,
*,
label: str = "",
+ on_change: Optional[Callable[[Optional[Numeric]], None]] = None,
) -> None:
value = start if value is None else value
if stop < start:
@@ -99,6 +101,7 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):
"step": step if step is not None else None,
"debounce": debounce,
},
+ on_change=on_change,
)
def _convert_value(self, value: Optional[Numeric]) -> Optional[Numeric]:
@@ -133,6 +136,7 @@ class slider(UIElement[Numeric, Numeric]):
- `debounce`: whether to debounce the slider to only send
the value on mouse-up or drag-end
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-slider"
@@ -146,6 +150,7 @@ class slider(UIElement[Numeric, Numeric]):
debounce: bool = False,
*,
label: str = "",
+ on_change: Optional[Callable[[Optional[Numeric]], None]] = None,
) -> None:
self._dtype = (
float
@@ -184,6 +189,7 @@ class slider(UIElement[Numeric, Numeric]):
"step": step if step is not None else None,
"debounce": debounce,
},
+ on_change=on_change,
)
def _convert_value(self, value: Numeric) -> Numeric:
@@ -209,16 +215,24 @@ class checkbox(UIElement[bool, bool]):
- `value`: default value, True or False
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-checkbox"
- def __init__(self, value: bool = False, *, label: str = "") -> None:
+ def __init__(
+ self,
+ value: bool = False,
+ *,
+ label: str = "",
+ on_change: Optional[Callable[[bool], None]] = None,
+ ) -> None:
super().__init__(
component_name=checkbox._name,
initial_value=value,
label=label,
args={},
+ on_change=on_change,
)
def _convert_value(self, value: bool) -> bool:
@@ -259,6 +273,7 @@ class radio(UIElement[Optional[str], Any]):
to option value
- `value`: default option name, if None, starts with nothing checked
- `label`: optional text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-radio"
@@ -269,6 +284,7 @@ class radio(UIElement[Optional[str], Any]):
value: Optional[str] = None,
*,
label: str = "",
+ on_change: Optional[Callable[[Any], None]] = None,
) -> None:
if not isinstance(options, dict):
if len(set(options)) != len(options):
@@ -282,6 +298,7 @@ class radio(UIElement[Optional[str], Any]):
args={
"options": list(options.keys()),
},
+ on_change=on_change,
)
def _convert_value(self, value: Optional[str]) -> Any:
@@ -310,6 +327,7 @@ class text(UIElement[str, str]):
- `kind`: input kind, one of `"text"`, `"password"`, `"email"`, or `"url"`
defaults to `"text"`
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-text"
@@ -321,6 +339,7 @@ class text(UIElement[str, str]):
kind: Literal["text", "password", "email", "url"] = "text",
*,
label: str = "",
+ on_change: Optional[Callable[[str], None]] = None,
) -> None:
super().__init__(
component_name=text._name,
@@ -330,6 +349,7 @@ class text(UIElement[str, str]):
"placeholder": placeholder,
"kind": kind,
},
+ on_change=on_change,
)
def _convert_value(self, value: str) -> str:
@@ -356,6 +376,7 @@ class text_area(UIElement[str, str]):
- `value`: initial value of the text area
- `placeholder`: placeholder text to display when the text area is empty
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-text-area"
@@ -366,6 +387,7 @@ class text_area(UIElement[str, str]):
placeholder: str = "",
*,
label: str = "",
+ on_change: Optional[Callable[[str], None]] = None,
) -> None:
super().__init__(
component_name=text_area._name,
@@ -374,6 +396,7 @@ class text_area(UIElement[str, str]):
args={
"placeholder": placeholder,
},
+ on_change=on_change,
)
def _convert_value(self, value: str) -> str:
@@ -417,6 +440,7 @@ class dropdown(UIElement[List[str], Any]):
`None` value; when `None`, defaults to `True` when
`value` is `None`
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-dropdown"
@@ -428,6 +452,7 @@ class dropdown(UIElement[List[str], Any]):
allow_select_none: Optional[bool] = None,
*,
label: str = "",
+ on_change: Optional[Callable[[Any], None]] = None,
) -> None:
if not isinstance(options, dict):
options = {option: option for option in options}
@@ -456,6 +481,7 @@ class dropdown(UIElement[List[str], Any]):
"options": list(self.options.keys()),
"allow-select-none": allow_select_none,
},
+ on_change=on_change,
)
def _convert_value(self, value: list[str]) -> Any:
@@ -491,6 +517,7 @@ class multiselect(UIElement[List[str], List[object]]):
to option value
- `value`: a list of initially selected options
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-multiselect"
@@ -501,6 +528,7 @@ class multiselect(UIElement[List[str], List[object]]):
value: Optional[Sequence[str]] = None,
*,
label: str = "",
+ on_change: Optional[Callable[[List[object]], None]] = None,
) -> None:
if not isinstance(options, dict):
options = {option: option for option in options}
@@ -515,6 +543,7 @@ class multiselect(UIElement[List[str], List[object]]):
args={
"options": list(self.options.keys()),
},
+ on_change=on_change,
)
def _convert_value(self, value: list[str]) -> list[object]:
@@ -565,6 +594,7 @@ class table(UIElement[List[str], List[object]]):
- `selection`: 'single' or 'multi' to enable row selection, or `None` to
disable
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-table"
@@ -577,6 +607,7 @@ class table(UIElement[List[str], List[object]]):
selection: Optional[Literal["single", "multi"]] = "multi",
*,
label: str = "",
+ on_change: Optional[Callable[[List[object]], None]] = None,
) -> None:
if not isinstance(data, (list, tuple)):
raise ValueError("data must be a list or tuple.")
@@ -604,6 +635,7 @@ class table(UIElement[List[str], List[object]]):
"pagination": pagination,
"selection": selection,
},
+ on_change=on_change,
)
@property
@@ -659,6 +691,7 @@ class button(UIElement[Any, Any]):
- `kind`: 'neutral', 'success', 'warn', or 'danger'
- `disabled`: whether the button is disabled
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-button"
@@ -671,6 +704,7 @@ class button(UIElement[Any, Any]):
disabled: bool = False,
*,
label: str = "click here",
+ on_change: Optional[Callable[[Any], None]] = None,
) -> None:
self._on_click = (lambda _: value) if on_click is None else on_click
self._initial_value = value
@@ -683,6 +717,7 @@ class button(UIElement[Any, Any]):
"kind": kind,
"disabled": disabled,
},
+ on_change=on_change,
)
def _convert_value(self, value: Any) -> Any:
@@ -779,6 +814,7 @@ class file(UIElement[List[Tuple[str, str]], Sequence[FileUploadResults]]):
- `multiple`: if True, allow the user to upload multiple files
- `kind`: `"button"` or `"area"`
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-file"
@@ -790,6 +826,9 @@ class file(UIElement[List[Tuple[str, str]], Sequence[FileUploadResults]]):
kind: Literal["button", "area"] = "button",
*,
label: str = "",
+ on_change: Optional[
+ Callable[[Sequence[FileUploadResults]], None]
+ ] = None,
) -> None:
super().__init__(
component_name=file._name,
@@ -800,6 +839,7 @@ class file(UIElement[List[Tuple[str, str]], Sequence[FileUploadResults]]):
"multiple": multiple,
"kind": kind,
},
+ on_change=on_change,
)
def _convert_value(
@@ -867,6 +907,7 @@ class date(UIElement[str, dt.date]):
- else if `None` and `start` is not `None`, defaults to `start`;
- else if `None` and `stop` is not `None`, defaults to `stop`
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-date-picker"
@@ -880,6 +921,7 @@ class date(UIElement[str, dt.date]):
value: Optional[dt.date | str] = None,
*,
label: str = "",
+ on_change: Optional[Callable[[dt.date], None]] = None,
) -> None:
if isinstance(start, str):
start = self._convert_value(start)
@@ -920,6 +962,7 @@ class date(UIElement[str, dt.date]):
"start": self._start.isoformat(),
"stop": self._stop.isoformat(),
},
+ on_change=on_change,
)
def _convert_value(self, value: str) -> dt.date:
@@ -984,6 +1027,7 @@ class form(UIElement[Optional[JSONTypeBound], Optional[T]]):
- `element`: the element to wrap
- `label`: text label for the form
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-form"
@@ -993,6 +1037,7 @@ class form(UIElement[Optional[JSONTypeBound], Optional[T]]):
element: UIElement[JSONTypeBound, T],
*,
label: str = "",
+ on_change: Optional[Callable[[Optional[T]], None]] = None,
) -> None:
self.element = element._clone()
super().__init__(
@@ -1001,6 +1046,7 @@ class form(UIElement[Optional[JSONTypeBound], Optional[T]]):
label=label,
args={"element-id": self.element._id},
slotted_html=self.element.text,
+ on_change=on_change,
)
def _convert_value(self, value: Optional[JSONTypeBound]) -> Optional[T]:
diff --git a/marimo/_plugins/ui/_impl/microphone.py b/marimo/_plugins/ui/_impl/microphone.py
index 36903dc084..014726dda4 100644
--- a/marimo/_plugins/ui/_impl/microphone.py
+++ b/marimo/_plugins/ui/_impl/microphone.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import base64
import io
-from typing import Final
+from typing import Callable, Final, Optional
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import UIElement
@@ -34,6 +34,7 @@ class microphone(UIElement[str, io.BytesIO]):
**Initialization Args.**
- `label`: optional text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
name: Final[str] = "marimo-microphone"
@@ -42,12 +43,14 @@ class microphone(UIElement[str, io.BytesIO]):
self,
*,
label: str = "",
+ on_change: Optional[Callable[[io.BytesIO], None]] = None,
) -> None:
super().__init__(
component_name=microphone.name,
initial_value="",
label=label,
args={},
+ on_change=on_change,
)
def _convert_value(self, value: str) -> io.BytesIO:
diff --git a/marimo/_plugins/ui/_impl/refresh.py b/marimo/_plugins/ui/_impl/refresh.py
index d32edf0c4c..cf476bc18d 100644
--- a/marimo/_plugins/ui/_impl/refresh.py
+++ b/marimo/_plugins/ui/_impl/refresh.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Final, Optional, Union
+from typing import Callable, Final, Optional, Union
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import UIElement
@@ -41,6 +41,7 @@ class refresh(UIElement[int, int]):
the refresh button will not be displayed with a dropdown for auto-refresh.
- `default_interval`: The default value of the refresh interval.
- `label`: optional text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
name: Final[str] = "marimo-refresh"
@@ -51,6 +52,7 @@ class refresh(UIElement[int, int]):
default_interval: Optional[Union[int, float, str]] = None,
*,
label: str = "",
+ on_change: Optional[Callable[[int], None]] = None,
) -> None:
if default_interval and not isinstance(
default_interval, (int, float, str)
@@ -92,6 +94,7 @@ class refresh(UIElement[int, int]):
"options": resolved_options,
"default-interval": default_interval,
},
+ on_change=on_change,
)
def _convert_value(self, value: int) -> int:
diff --git a/marimo/_plugins/ui/_impl/switch.py b/marimo/_plugins/ui/_impl/switch.py
index c9f74eb5c0..30383e5640 100644
--- a/marimo/_plugins/ui/_impl/switch.py
+++ b/marimo/_plugins/ui/_impl/switch.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Final
+from typing import Callable, Final, Optional
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import UIElement
@@ -26,11 +26,18 @@ class switch(UIElement[bool, bool]):
- `value`: default value, True or False
- `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
"""
_name: Final[str] = "marimo-switch"
- def __init__(self, value: bool = False, *, label: str = "") -> None:
+ def __init__(
+ self,
+ value: bool = False,
+ *,
+ label: str = "",
+ on_change: Optional[Callable[[bool], None]] = None,
+ ) -> None:
if not isinstance(value, bool):
raise ValueError(
"Invalid type: `value` must be a bool, but got %s"
@@ -46,6 +53,7 @@ class switch(UIElement[bool, bool]):
initial_value=value,
label=label,
args={},
+ on_change=on_change,
)
def _convert_value(self, value: bool) -> bool:
diff --git a/marimo/_plugins/ui/_impl/test_input.py b/marimo/_plugins/ui/_impl/test_input.py
index 39a07fa759..f1c6628b31 100644
--- a/marimo/_plugins/ui/_impl/test_input.py
+++ b/marimo/_plugins/ui/_impl/test_input.py
@@ -143,5 +143,15 @@ def test_button() -> None:
assert button.value == 2
+def test_on_change() -> None:
+ state = []
+ button = ui.checkbox(on_change=lambda v: state.append(v))
+ assert not state
+ button._update(False)
+ assert state == [False]
+ button._update(True)
+ assert state == [False, True]
+
+
# TODO(akshayka): test file
# TODO(akshayka): test date
diff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.py
index 23d423a66c..f768d02e78 100644
--- a/marimo/_runtime/cell_runner.py
+++ b/marimo/_runtime/cell_runner.py
@@ -6,14 +6,18 @@ import pprint
import re
import sys
import traceback
+from collections.abc import Container
from dataclasses import dataclass
-from typing import Any, Optional
+from typing import TYPE_CHECKING, Any, Optional
from marimo._ast.cell import CellId_t, execute_cell
from marimo._output import formatting
from marimo._runtime import dataflow
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
+if TYPE_CHECKING:
+ from marimo._runtime.state import State
+
def cell_filename(cell_id: CellId_t) -> str:
"""Filename to use when running cells through exec."""
@@ -150,6 +154,10 @@ class Runner:
self.interrupted = False
self.exceptions: dict[CellId_t, Exception] = {}
+ self._run_position = {
+ cell_id: index for index, cell_id in enumerate(self.cells_to_run)
+ }
+
def cancel(self, cell_id: CellId_t) -> None:
"""Mark a cell (and its descendants) as cancelled."""
self.cells_cancelled[cell_id] = set(
@@ -168,6 +176,80 @@ class Runner:
"""Whether there are more cells to run."""
return not self.interrupted and len(self.cells_to_run) > 0
+ def _get_run_position(self, cell_id: CellId_t) -> Optional[int]:
+ """Position in the original run queue"""
+ return (
+ self._run_position[cell_id]
+ if cell_id in self._run_position
+ else None
+ )
+
+ def _runs_after(
+ self, source: CellId_t, target: CellId_t
+ ) -> Optional[bool]:
+ """Compare run positions.
+
+ Returns `True` if source runs after target, `False` if target runs
+ after source, or `None` if not comparable
+ """
+ source_pos = self._get_run_position(source)
+ target_pos = self._get_run_position(target)
+ if source_pos is None or target_pos is None:
+ return None
+ return source_pos > target_pos
+
+ def resolve_state_updates(
+ self,
+ state_updates: dict[State[Any], CellId_t],
+ errored_cells: Container[CellId_t],
+ ) -> set[CellId_t]:
+ """
+ Get cells that need to be run as a consequence of state updates
+
+ A cell is marked as needing to run if all of the following are true:
+
+ 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.
+ 4. It is not errored (unable to run) or cancelled.
+ 5. It has among its refs the state object whose setter
+ was invoked.
+
+ (3) means that a state update in a given cell will never re-trigger
+ the same cell to run. This is similar to how interacting with
+ a UI element in the cell that created it won't re-trigger the cell,
+ and this behavior is useful when tieing UI elements together with a
+ state object.
+
+ **Arguments.**
+
+ - state_updates: mapping from state object to the cell that last ran
+ its setter
+ - errored_cells: cell ids that are unable to run
+ """
+ # No updates when the runner is interrupted (condition 1)
+ if self.interrupted:
+ return set()
+
+ cids_to_run: set[CellId_t] = set()
+ for state, setter_cell_id in state_updates.items():
+ for cid, cell in self.graph.cells.items():
+ # Don't re-run cells that already ran with new state (2)
+ if self._runs_after(source=cid, target=setter_cell_id):
+ continue
+ # No self-loops (3)
+ if cid == setter_cell_id:
+ continue
+ # No errorred/cancelled cells (4)
+ if cid in errored_cells or self.cancelled(cid):
+ continue
+ # State object in refs (5)
+ for ref in cell.refs:
+ # run this cell if any of its refs match the state
+ if ref in self.glbls and self.glbls[ref] == state:
+ cids_to_run.add(cid)
+ return cids_to_run
+
def pop_cell(self) -> CellId_t:
"""Get the next cell to run."""
return self.cells_to_run.pop(0)
diff --git a/marimo/_runtime/conftest.py b/marimo/_runtime/conftest.py
new file mode 100644
index 0000000000..032e23a911
--- /dev/null
+++ b/marimo/_runtime/conftest.py
@@ -0,0 +1,55 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import textwrap
+from typing import Any, Generator
+
+import pytest
+
+from marimo._plugins.ui._core.registry import UIElementRegistry
+from marimo._runtime.context import get_context
+from marimo._runtime.requests import ExecutionRequest
+from marimo._runtime.runtime import Kernel
+
+
+class _MockStream:
+ def write(self, op: str, data: dict[Any, Any]) -> None:
+ del op
+ del data
+ pass
+
+
+# fixture that provides a kernel (and tears it down)
+def k() -> Generator[Kernel, None, None]:
+ k = Kernel()
+ get_context().initialize(
+ kernel=k,
+ ui_element_registry=UIElementRegistry(),
+ stream=_MockStream(), # type: ignore
+ stdout=None,
+ stderr=None,
+ )
+ yield k
+ # have to teardown the runtime context because it's a global
+ get_context()._kernel = None
+ get_context()._ui_element_registry = None
+ get_context()._stream = None
+ get_context()._initialized = False
+
+
+# Factory to create ExecutionRequests and abstract away cell ID
+class ExecReqProvider:
+ def __init__(self) -> None:
+ self.counter = 0
+
+ def get(self, code: str) -> ExecutionRequest:
+ key = str(self.counter)
+ self.counter += 1
+ return ExecutionRequest(key, textwrap.dedent(code))
+
+
+# fixture that provides an ExecReqProvider
+def exec_req() -> Generator[ExecReqProvider, None, None]:
+ yield ExecReqProvider()
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 02e951ff1e..764c56826b 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -13,6 +13,7 @@ import threading
import time
import traceback
from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
from queue import Empty as QueueEmpty
from typing import Any, Iterator, Optional
@@ -57,6 +58,7 @@ from marimo._runtime.requests import (
SetUIElementValueRequest,
StopRequest,
)
+from marimo._runtime.state import State
from marimo._runtime.validate_graph import check_for_errors
from marimo.config._config import configure
@@ -72,11 +74,13 @@ def defs() -> tuple[str, ...]:
- tuple of the currently executing cell's defs.
"""
ctx = get_context()
- if ctx.initialized and ctx.kernel.cell_id is not None:
+ if ctx.initialized and ctx.kernel.execution_context is not None:
return tuple(
sorted(
defn
- for defn in ctx.kernel.graph.cells[ctx.kernel.cell_id].defs
+ for defn in ctx.kernel.graph.cells[
+ ctx.kernel.execution_context.cell_id
+ ].defs
)
)
return tuple()
@@ -95,11 +99,13 @@ def refs() -> tuple[str, ...]:
unshadowed_builtins = set(builtins.__dict__.keys()).difference(
set(ctx.kernel.graph.definitions.keys())
)
- if ctx.initialized and ctx.kernel.cell_id is not None:
+ if ctx.initialized and ctx.kernel.execution_context is not None:
return tuple(
sorted(
defn
- for defn in ctx.kernel.graph.cells[ctx.kernel.cell_id].refs
+ for defn in ctx.kernel.graph.cells[
+ ctx.kernel.execution_context.cell_id
+ ].refs
# exclude builtins that have not been shadowed
if defn not in unshadowed_builtins
)
@@ -107,6 +113,12 @@ def refs() -> tuple[str, ...]:
return tuple()
+@dataclass
+class ExecutionContext:
+ cell_id: CellId_t
+ setting_element_value: bool
+
+
class Kernel:
def __init__(self) -> None:
self.globals: dict[Any, Any] = {
@@ -114,10 +126,14 @@ class Kernel:
"__builtins__": globals()["__builtins__"],
}
self.graph = dataflow.DirectedGraph()
- self.executing = False
- self.cell_id: Optional[CellId_t] = None
+ self.execution_context: Optional[ExecutionContext] = None
+ # initializers to override construction of ui elements
self.ui_initializers: dict[str, Any] = {}
+ # errored cells
self.errors: dict[CellId_t, tuple[Error, ...]] = {}
+ # Mapping from state to the cell when its setter
+ # was invoked. New state updates evict older ones.
+ self.state_updates: dict[State[Any], CellId_t] = {}
self.completion_thread: Optional[threading.Thread] = None
self.completion_queue: queue.Queue[CompletionRequest] = queue.Queue()
@@ -127,17 +143,19 @@ class Kernel:
exec("import marimo as __marimo__", self.globals)
@contextlib.contextmanager
- def _execution_ctx(self, cell_id: CellId_t) -> Iterator[None]:
- self.executing = True
- self.cell_id = cell_id
+ def _install_execution_context(
+ self, cell_id: CellId_t, setting_element_value: bool = False
+ ) -> Iterator[None]:
+ self.execution_context = ExecutionContext(
+ cell_id, setting_element_value
+ )
with get_context().provide_ui_ids(str(cell_id)), redirect_streams(
cell_id
):
try:
yield
finally:
- self.executing = False
- self.cell_id = None
+ self.execution_context = None
def _try_registering_cell(
self, cell_id: CellId_t, code: str
@@ -267,7 +285,7 @@ class Kernel:
execution_requests: Sequence[ExecutionRequest],
deletion_requests: Sequence[DeleteRequest],
) -> set[CellId_t]:
- """Add and remove cells to the graph.
+ """Add and remove cells to/from the graph.
This method adds the cells in `execution_requests` to the kernel's
graph (deleting old versions of these cells, if any), and removes the
@@ -430,12 +448,25 @@ class Kernel:
return descendants
def _run_cells(self, cell_ids: set[CellId_t]) -> None:
+ """Run cells and any state updates they trigger"""
+ while cells_with_stale_state := self._run_cells_internal(cell_ids):
+ LOGGER.debug("Running state updates ...")
+ cell_ids = dataflow.transitive_closure(
+ self.graph, cells_with_stale_state
+ )
+ LOGGER.debug("Finished run.")
+ write_completed_run()
+
+ def _run_cells_internal(self, cell_ids: set[CellId_t]) -> set[CellId_t]:
+ """Run cells, send outputs to frontends"""
LOGGER.debug("preparing to evaluate cells %s", cell_ids)
for cid in cell_ids:
write_queued(cell_id=cid)
runner = cell_runner.Runner(
- cell_ids=cell_ids, graph=self.graph, glbls=self.globals
+ cell_ids=cell_ids,
+ graph=self.graph,
+ glbls=self.globals,
)
# I/O
@@ -459,13 +490,13 @@ class Kernel:
# State clean-up: don't leak names, UI elements, ...
self._invalidate_cell_state(cell_id)
- with self._execution_ctx(cell_id):
+ with self._install_execution_context(cell_id):
run_result = runner.run(cell_id)
if run_result.success():
formatted_output = run_result.format_output()
if formatted_output.traceback is not None:
- with self._execution_ctx(cell_id):
+ with self._install_execution_context(cell_id):
sys.stderr.write(formatted_output.traceback)
write_output(
channel=formatted_output.channel,
@@ -477,7 +508,7 @@ class Kernel:
LOGGER.debug("Cell %s was stopped via mo.stop()", cell_id)
formatted_output = run_result.format_output()
if formatted_output.traceback is not None:
- with self._execution_ctx(cell_id):
+ with self._install_execution_context(cell_id):
sys.stderr.write(formatted_output.traceback)
write_output(
channel=formatted_output.channel,
@@ -574,8 +605,20 @@ class Kernel:
cell_id=cid,
)
- LOGGER.debug("Finished run.")
- write_completed_run()
+ cells_with_stale_state = runner.resolve_state_updates(
+ self.state_updates, self.errors
+ )
+ self.state_updates.clear()
+ return cells_with_stale_state
+
+ def register_state_update(self, state: State[Any]) -> None:
+ """Register a state object as having been updated.
+
+ Should be called when a state's setter is called.
+ """
+ # store the state and the currently executing cell
+ assert self.execution_context is not None
+ self.state_updates[state] = self.execution_context.cell_id
def delete(self, request: DeleteRequest) -> None:
"""Delete a cell from kernel and graph."""
@@ -588,11 +631,22 @@ class Kernel:
)
def run(self, execution_requests: Sequence[ExecutionRequest]) -> None:
+ """Run cells and their descendants.
+
+ The cells may be cells already existing in the graph or new cells.
+ Adds the cells in `execution_requests` to the graph before running
+ them.
+ """
+
self._run_cells(
self.mutate_graph(execution_requests, deletion_requests=[])
)
def set_ui_element_value(self, request: SetUIElementValueRequest) -> None:
+ """Set the value of a UI element bound to a global variable.
+
+ Runs cells that reference the UI element by name.
+ """
referring_cells = set()
for object_id, value in request.ids_and_values:
try:
@@ -611,7 +665,11 @@ class Kernel:
LOGGER.debug("Could not find UIElement with id %s", object_id)
continue
- component._update(value)
+ with self._install_execution_context(
+ get_context().ui_element_registry.get_cell(object_id),
+ setting_element_value=True,
+ ):
+ component._update(value)
bound_names = get_context().ui_element_registry.bound_names(
object_id
)
@@ -649,6 +707,7 @@ class Kernel:
self.ui_initializers = {}
def complete(self, request: CompletionRequest) -> None:
+ """Code completion"""
if self.completion_thread is None:
self.completion_thread = threading.Thread(
target=complete,
@@ -736,8 +795,9 @@ def launch_kernel(
break
# TODO(akshayka): if kernel is in `run` but not executing,
- # it won't be interrupted, which isn't right
- if kernel.executing:
+ # it won't be interrupted, which isn't right ... but the
+ # probability of that happening is low.
+ if kernel.execution_context is not None:
write_interrupted()
raise MarimoInterrupt
diff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.py
new file mode 100644
index 0000000000..836608afd6
--- /dev/null
+++ b/marimo/_runtime/state.py
@@ -0,0 +1,117 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import types
+from typing import Callable, Generic, TypeVar
+
+from marimo._output.rich_help import mddoc
+from marimo._runtime.context import get_context
+
+T = TypeVar("T")
+
+
+class State(Generic[T]):
+ """Mutable reactive state"""
+
+ def __init__(self, value: T) -> None:
+ self._value = value
+
+ def __call__(self) -> T:
+ return self._value
+
+ def _set_value(self, update: T | Callable[[T], T]) -> None:
+ """Update the state and register the update with the kernel"""
+ self._value = (
+ update(self._value)
+ if isinstance(update, (types.MethodType, types.FunctionType))
+ else update
+ )
+ ctx = get_context()
+ if not ctx.initialized:
+ return
+ kernel = ctx.kernel
+ assert kernel is not None
+ kernel.register_state_update(self)
+
+
+@mddoc
+def state(value: T) -> tuple[State[T], Callable[[T], None]]:
+ """Mutable reactive state
+
+ This function takes an initial value and returns:
+
+ - a getter function that reads the state value
+ - 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.
+
+ You can use this function in conjunction with `UIElement` `on_change`
+ handlers to trigger side-effects when an element's value is updated. For
+ example, you can tie multiple UI elements to derive their values from
+ shared state.
+
+ **Basic Usage.**
+
+
+ Create state:
+
+ ```python
+ get_count, set_count = mo.state(0)
+ ```
+
+ Read the value:
+
+ ```python
+ get_count()
+ ```
+
+ Update the state:
+
+ ```
+ set_count(1)
+ ```
+
+ Update the state based on the current value:
+
+ ```
+ set_count(lambda value: value + 1)
+ ```
+
+ *Note: Never mutate the state directly. You should only change its
+ value through its setter.*
+
+ **Synchronizing multiple UI elements.**
+
+ ```python
+ get_state, set_state = mo.state(0)
+ ```
+
+ ```python
+ # updating the state through the slider will recreate the number (below)
+ slider = mo.ui.slider(0, 100, value=get_state(), on_change=set_state)
+ ```
+
+ ```python
+ # updating the state through the number will recreate the slider (above)
+ number = mo.ui.number(0, 100, value=get_state(), on_change=set_state)
+ ```
+
+ ```python
+ # slider and number are synchronized to have the same value (try it!)
+ [slider, number]
+ ```
+
+ **Args**:
+
+ - `value`: initial value of the state
+
+ **Returns**:
+
+ - getter function that retrieves the state value
+ - 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)
+ return state_instance, state_instance._set_value
diff --git a/marimo/_runtime/test_control_flow.py b/marimo/_runtime/test_control_flow.py
index b1dac0d4a1..3283bebdd8 100644
--- a/marimo/_runtime/test_control_flow.py
+++ b/marimo/_runtime/test_control_flow.py
@@ -1,44 +1,13 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, Generator
-
-import pytest
-
-from marimo._plugins.ui._core.registry import UIElementRegistry
from marimo._runtime import cell_runner, control_flow
-from marimo._runtime.context import get_context
from marimo._runtime.requests import (
ExecutionRequest,
)
from marimo._runtime.runtime import Kernel
-class _MockStream:
- def write(self, op: str, data: dict[Any, Any]) -> None:
- del op
- del data
- pass
-
-
-# fixture that provides a kernel (and tears it down)
-def k() -> Generator[Kernel, None, None]:
- k = Kernel()
- get_context().initialize(
- kernel=k,
- ui_element_registry=UIElementRegistry(),
- stream=_MockStream(), # type: ignore
- stdout=None,
- stderr=None,
- )
- yield k
- get_context()._kernel = None
- get_context()._ui_element_registry = None
- get_context()._stream = None
- get_context()._initialized = False
-
-
def test_stop_false(k: Kernel) -> None:
k.run(
[
diff --git a/marimo/_runtime/test_runtime.py b/marimo/_runtime/test_runtime.py
index 66d1e70da2..5add4d63e8 100644
--- a/marimo/_runtime/test_runtime.py
+++ b/marimo/_runtime/test_runtime.py
@@ -1,9 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, Generator, Sequence
-
-import pytest
+from typing import Sequence
from marimo._messaging.errors import (
CycleError,
@@ -12,8 +10,6 @@ from marimo._messaging.errors import (
MultipleDefinitionError,
)
from marimo._plugins.ui._core.ids import IDProvider
-from marimo._plugins.ui._core.registry import UIElementRegistry
-from marimo._runtime.context import get_context
from marimo._runtime.dataflow import Edge
from marimo._runtime.requests import (
CreationRequest,
@@ -24,31 +20,6 @@ from marimo._runtime.requests import (
from marimo._runtime.runtime import Kernel
-class _MockStream:
- def write(self, op: str, data: dict[Any, Any]) -> None:
- del op
- del data
- pass
-
-
-# fixture that provides a kernel (and tears it down)
-def k() -> Generator[Kernel, None, None]:
- k = Kernel()
- get_context().initialize(
- kernel=k,
- ui_element_registry=UIElementRegistry(),
- stream=_MockStream(), # type: ignore
- stdout=None,
- stderr=None,
- )
- yield k
- get_context()._kernel = None
- get_context()._ui_element_registry = None
- get_context()._stream = None
- get_context()._initialized = False
-
-
def _check_edges(error: Error, expected_edges: Sequence[Edge]) -> None:
assert isinstance(error, CycleError)
assert len(error.edges) == len(expected_edges)
diff --git a/marimo/_runtime/test_state.py b/marimo/_runtime/test_state.py
new file mode 100644
index 0000000000..613fdf25e2
--- /dev/null
+++ b/marimo/_runtime/test_state.py
@@ -0,0 +1,127 @@
+# Copyright 2023 Marimo. All rights reserved.
+from marimo._runtime.conftest import ExecReqProvider
+from marimo._runtime.runtime import Kernel
+
+
+def test_set_and_state(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("state, set_state = mo.state(0)"),
+ exec_req.get("x = state()"),
+ exec_req.get(
+ """
+ x
+ if x == 0:
+ set_state(1)
+ """
+ ),
+ ]
+ )
+
+ assert k.globals["x"] == 1
+
+
+def test_set_and_get_iteration(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("state, set_state = mo.state(0)"),
+ exec_req.get("x = state()"),
+ exec_req.get(
+ """
+ x
+ if x < 5:
+ set_state(x + 1)
+ """
+ ),
+ ]
+ )
+
+ assert k.globals["x"] == 5
+
+
+def test_no_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)"),
+ exec_req.get("x = state(); set_state(1)"),
+ ]
+ )
+
+ assert k.globals["x"] == 0
+
+
+def test_update_with_function(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("state, set_state = mo.state(0)"),
+ exec_req.get("set_state(lambda v: v + 1)"),
+ exec_req.get("x = state()"),
+ ]
+ )
+
+ assert k.globals["x"] == 1
+
+
+def test_set_to_callable_object(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("state, set_state = mo.state(0)"),
+ exec_req.get(
+ """
+ class F:
+ called = False
+ def __call__(self):
+ self.called = True
+ f = F()
+ """
+ ),
+ exec_req.get("set_state(f)"),
+ exec_req.get("x = state()"),
+ ]
+ )
+
+ # state should be an `F` instance that hasn't been called
+ assert not k.globals["x"].called
+
+
+def test_non_stale_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get(
+ """
+ class ns:
+ ...
+ private = ns()
+ private.counter = 0
+ """
+ ),
+ exec_req.get("state, set_state = mo.state(0)"),
+ exec_req.get("set_state(1); x = 0"),
+ # this cell runs as a result of the dag; the setter above
+ # shouldn't cause it to re-run, even though it calls the getter
+ exec_req.get("x; private.counter += state()"),
+ ]
+ )
+
+ assert k.globals["private"].counter == 1
+
+
+def test_cancelled_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("state, set_state = mo.state(0)"),
+ exec_req.get("set_state(1); x = 0; raise ValueError"),
+ # this cell shouldn't run because it was cancelled by
+ # its ancestor raising an error
+ exec_req.get("x; y = state()"),
+ ]
+ )
+
+ assert "y" not in k.globals
diff --git a/marimo/_smoke_tests/state.py b/marimo/_smoke_tests/state.py
new file mode 100644
index 0000000000..fa77406212
--- /dev/null
+++ b/marimo/_smoke_tests/state.py
@@ -0,0 +1,95 @@
+import marimo
+
+__generated_with = "0.1.4"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __():
+ import math
+ return math,
+
+
+def __():
+ import random
+ return random,
+
+
+def __():
+ import time
+ return time,
+
+
+def __(mo):
+ get_state, set_state = mo.state(0)
+ return get_state, set_state
+
+
+def __(get_state, set_state):
+ # No self-loops: shouldn't be a cycle
+ set_state(get_state())
+ return
+
+
+def __(get_state):
+ get_state()
+ return
+
+
+def __(mo, set_state):
+ _on_click = lambda _: set_state(lambda v: v + 1)
+ button = mo.ui.button(
+ value=0, on_click=_on_click
+ )
+ button
+ return button,
+
+
+def __(mo):
+ # tie two number components together
+ get_angle, set_angle = mo.state(0)
+ return get_angle, set_angle
+
+
+def __(get_angle, mo, set_angle):
+ degrees = mo.ui.number(
+ 0, 360, step=1, value=get_angle(), on_change=set_angle, label="degrees"
+ )
+ return degrees,
+
+
+def __(get_angle, math, mo, set_angle):
+ radians = mo.ui.number(
+ 0,
+ 2*math.pi,
+ step=0.01,
+ value=get_angle() * math.pi / 180,
+ on_change=lambda v: set_angle(v * 180 / math.pi),
+ label="radians"
+ )
+ return radians,
+
+
+def __(degrees, radians):
+ degrees, radians
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_tutorials/ui.py b/marimo/_tutorials/ui.py
index 3ca3f0a66c..ea0b37e445 100644
--- a/marimo/_tutorials/ui.py
+++ b/marimo/_tutorials/ui.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
import marimo
-__generated_with = "0.0.5"
+__generated_with = "0.1.4"
app = marimo.App()
@@ -170,23 +170,130 @@ def __(composite_elements, documentation):
@app.cell
def __(mo):
+ mo.md("## State")
+ return
+
+
+def __(mo):
+ mo.md(
+ """
+ **Heads up!**
+
+ The rest of this tutorial covers state, an advanced topic. Feel free
+ to return here later, if or when you find yourself
+ limited in building interactive stateful apps.
+ """
+ ).callout(kind="warn")
+ return
+
+
+def __(mo):
+ mo.md(
+ """
+ You can build powerful interactive notebooks and apps using just
+ `mo.ui` and reactivity.
+
+ Sometimes, however, you might want interactions to mutate **state**.
+ Maybe you're building a checklist, and you want to maintain a list
+ of action items. Or maybe you want to tie two different UI elements, so
+ that updating one updates the other.
+
+ For these and other cases, marimo provides the function `mo.state`, which
+ creates state returns a getter function and a setter function. When you
+ call the setter function in one cell, all other
+ cells that reference the getter via a global variable are automatically
+ run (similar to UI elements).
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.accordion({"Documentation on `mo.state`": mo.doc(mo.state)})
+ return
+
+
+def __(mo):
+ mo.md(
+ """
+ ### Creating state
+
+ `mo.state` takes an initial state value as its argument, and returns
+
+ - a function that returns the state value;
+ - a function that updates the state value.
+
+ For exaxmple,
+
+ ```python
+ get_counter, set_counter = mo.state(0)
+ ```
+ """
+ )
+ return
+
+
+def __(mo):
+ get_counter, set_counter = mo.state(0)
+ return get_counter, set_counter
+
+
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: assign state getters to global variables": (
+ """
+ Calling a state's setter function will only
+ trigger reactive execution if the corresponding getter is
+ assigned to and referenced via a global variable.
+ """
+ ),
+ "Tip: use state sparingly": (
+ """
+ You can get far using just `mo.ui`, without state. That said,
+ judiciously using state can simplify the implementation of highly
+ interactive notebooks/apps, and also enables new use cases.
+ """
+ ),
+ }
+ )
+ return
+
+
+def __(get_counter, mo):
mo.md(
+ f"""
+ Acccess the value of the state via its getter: `get_counter()`
+ returned **{get_counter()}**
"""
- ## Example: A task list
+ )
+ return
- The next three cells implement a task list. The task list is
- built using three basic UI elements:
- - `mo.checkbox` for the task items
- - `mo.text` for the task entry input
- - `mo.button` for adding and removing tasks
+def __(mo):
+ mo.md(
+ """
+ ### Setting State
- and one composite element:
+ Set an element's state by calling its setter function.
- - `mo.array` for maintaining a list of tasks.
+ - Call it with a new value: `set_counter(1)`
+ - Call it with a function that takes the current value and returns a new
+ one: `set_counter(lambda count: count + 1)`
- This is an advanced example. You can get far with marimo without
- ever having to implement a stateful element like this one.
+ **State updates are reactive.** When you call a state's setter in one
+ cell, _all other cells that reference the state getter via a global
+ variable_ are automatically
+ run with the new state value. This is similar to how interacting with
+ a UI element automatically runs all cells that use the element.
"""
)
return
@@ -194,84 +301,215 @@ def __(mo):
@app.cell
def __(mo):
- # A text input for entering a task
- task = mo.ui.text(placeholder="a task ...")
+ mo.md(
+ """
+ **The `on_change` callback.** Every UI element takes an optional
+ `on_change` callback, a function
+ that takes the new value of the element and does anything with it. You can
+ use the setter function in an `on_change` callback to mutate state.
- class TaskListState:
+ **🌊 Try it!** Click the button below and watch what happens.
"""
- This class holds the state of the task list: the tasks (labels),
- and whether they've been completed (values).
+ )
+ return
+
+
+def __(mo, set_counter):
+ increment = mo.ui.button(
+ label="increment",
+ on_change=lambda _: set_counter(lambda v: v + 1),
+ )
+
+ decrement = mo.ui.button(
+ label="decrement",
+ on_change=lambda _: set_counter(lambda v: v - 1),
+ )
+
+ mo.hstack([increment, decrement], justify="center")
+ return decrement, increment
+
+
+def __(get_counter, mo):
+ mo.md(
+ f"""
+ The counter's current value is **{get_counter()}**!
+
+ This cell runs automatically on button click, even though it
+ doesn't reference either button.
"""
- def __init__(self):
- # The task labels
- self.labels = []
- # Whether each label is checked
- self.values = []
-
- def add_task(self):
- if task.value:
- # Add the current value of the task input to `self.labels`
- self.labels.append(task.value)
- # The task starts as incomplete
- self.values.append(False)
- return self
-
- def clear_tasks(self):
- # Remove all completed tasks from state
- self.labels[:] = [
- label
- for i, label in enumerate(self.labels)
- if not self.values[i]
- ]
- self.values[:] = [v for v in self.values if not v]
- return self
+ )
+ return
+
+
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: no self-loops": (
+ """
+ Calling a state's setter in one cell won't ever cause that same
+ cell to re-execute, even if it reads that state getter. This
+ prevents accidental infinite loops and makes some things, like
+ tying elements, easier."
+ """
+ )
+ }
+ )
+ return
+
+
+def __(mo):
+ mo.md("### Tied elements")
+ return
+
+
+def __(mo):
+ mo.md(
+ """
+ Use state to tie two UI elements to the same value.
+ """
+ )
+ return
+
+
+def __(mo):
+ get_shared_state, set_shared_state = mo.state(0)
+ return get_shared_state, set_shared_state
+
+
+def __(get_shared_state, mo, set_shared_state):
+ x = mo.ui.slider(
+ 0, 10, value=get_shared_state(), on_change=set_shared_state, label="$x$:"
+ )
+ return x,
+
+
+def __(get_shared_state, mo, set_shared_state):
+ x_plus_one = mo.ui.number(
+ 1,
+ 11,
+ value=get_shared_state() + 1,
+ on_change=lambda v: set_shared_state(v - 1),
+ label="$x + 1$:",
+ )
+ return x_plus_one,
+
+
+def __(x, x_plus_one):
+ [x, x_plus_one]
+ return
+
+
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: tying elements and cycles": (
+ """
+ To tie elements, you must `mo.state`, and the tied elements
+ must be created in different cells (since self-loops with state
+ are not allowed).
+ """
+ )
+ }
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ """
+ ### Example: Task list
+ """
+ )
+ return
+
+
+def __(dataclass, mo):
+ @dataclass
+ class Task:
+ name: str
+ done: bool = False
+
+
+ get_tasks, set_tasks = mo.state([])
+ task_list_mutated, set_task_list_mutated = mo.state(False)
+ return (
+ Task,
+ get_tasks,
+ set_task_list_mutated,
+ set_tasks,
+ task_list_mutated,
+ )
+
+
+def __(mo, task_list_mutated):
+ task_list_mutated
+
+ task_entry_box = mo.ui.text(placeholder="a task ...")
+ return task_entry_box,
+
+
+def __(Task, mo, set_task_list_mutated, set_tasks, task_entry_box):
+ def add_task():
+ if task_entry_box.value:
+ set_tasks(lambda v: v + [Task(task_entry_box.value)])
+ set_task_list_mutated(True)
+
+
+ def clear_tasks():
+ set_tasks(lambda v: [task for task in v if not task.done])
+ set_task_list_mutated(True)
- state = TaskListState()
- # Buttons to add and remove tasks; these buttons mutate state when they
- # are clicked.
add_task_button = mo.ui.button(
- value=state,
- on_click=lambda state: state.add_task(),
label="add task",
+ on_change=lambda _: add_task(),
)
clear_tasks_button = mo.ui.button(
- value=state,
- on_click=lambda state: state.clear_tasks(),
- label="clear completed tasks",
+ label="clear completed tasks", on_change=lambda _: clear_tasks()
)
- return TaskListState, add_task_button, clear_tasks_button, state, task
+ return add_task, add_task_button, clear_tasks, clear_tasks_button
@app.cell
-def __(add_task_button, clear_tasks_button, mo, state, task):
- # Construct the task list based on the task list state.
- #
- # This cell will re-run and reconstruct the task list with updated state
- # whenever either of the buttons are clicked, since they include references
- # to the button elements.
+def __(Task, get_tasks, mo, set_tasks):
task_list = mo.ui.array(
- [
- mo.ui.checkbox(value=v, label=l)
- for v, l in zip(state.values, state.labels)
- ],
+ [mo.ui.checkbox(value=task.done, label=task.name) for task in get_tasks()],
label="tasks",
+ on_change=lambda v: set_tasks(
+ lambda tasks: [
+ Task(task.name, done=v[i]) for i, task in enumerate(tasks)
+ ]
+ ),
)
+ return task_list,
+
- (
- task,
- add_task_button,
- clear_tasks_button,
- task_list if state.values else mo.md("No tasks! 🎉"),
+def __(add_task_button, clear_tasks_button, mo, task_entry_box):
+ mo.hstack(
+ [task_entry_box, add_task_button, clear_tasks_button], justify="start"
)
- return task_list,
+ return
@app.cell
-def __(state, task_list):
- # This cell runs whenever a task is checked or unchecked, updating the state
- state.values[:] = task_list.value
+def __(mo, task_list):
+ mo.as_html(task_list) if task_list.value else mo.md("No tasks! 🎉")
return
@@ -291,12 +529,16 @@ def __(mo):
@app.cell
def __(mo):
composite_elements = mo.ui.dropdown(
- options=dict(sorted({
- 'array': mo.ui.array,
- 'batch': mo.ui.batch,
- 'dictionary': mo.ui.dictionary,
- 'form': mo.ui.form,
- }.items())),
+ options=dict(
+ sorted(
+ {
+ "array": mo.ui.array,
+ "batch": mo.ui.batch,
+ "dictionary": mo.ui.dictionary,
+ "form": mo.ui.form,
+ }.items()
+ )
+ ),
)
return composite_elements,
@@ -304,21 +546,25 @@ def __(mo):
@app.cell
def __(mo):
basic_ui_elements = mo.ui.dropdown(
- options=dict(sorted({
- 'button': mo.ui.button,
- 'checkbox': mo.ui.checkbox,
- 'date': mo.ui.date,
- 'dropdown': mo.ui.dropdown,
- 'file': mo.ui.file,
- 'multiselect': mo.ui.multiselect,
- 'number': mo.ui.number,
- 'radio': mo.ui.radio,
- 'slider': mo.ui.slider,
- 'switch': mo.ui.switch,
- 'table': mo.ui.table,
- 'text': mo.ui.text,
- 'text_area': mo.ui.text_area,
- }.items())),
+ options=dict(
+ sorted(
+ {
+ "button": mo.ui.button,
+ "checkbox": mo.ui.checkbox,
+ "date": mo.ui.date,
+ "dropdown": mo.ui.dropdown,
+ "file": mo.ui.file,
+ "multiselect": mo.ui.multiselect,
+ "number": mo.ui.number,
+ "radio": mo.ui.radio,
+ "slider": mo.ui.slider,
+ "switch": mo.ui.switch,
+ "table": mo.ui.table,
+ "text": mo.ui.text,
+ "text_area": mo.ui.text_area,
+ }.items()
+ )
+ ),
)
return basic_ui_elements,
@@ -393,7 +639,7 @@ def __(mo):
def __(mo):
def show_element(element):
if element is not None:
- return mo.hstack([element], "center")
+ return mo.hstack([element], "center")
return show_element,
@@ -424,6 +670,12 @@ def __(mo):
return documentation,
+def __():
+ from dataclasses import dataclass
+ return dataclass,
+
+
@app.cell
def __():
import marimo as mo