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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
docs: recipes (#374)
Akshay Agrawal247715e351c0
diff --git a/docs/faq.md b/docs/faq.mdindex cd53f75b3e..2137a862dc 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -93,6 +93,9 @@ Interactive UI elements like sliders are available in `marimo.ui`.it (`slider` or `mo.md(f"Choose a value: {slider}")`)- Read its current value in another cell via its `value` attribute (`slider.value`)+_When a UI element bound to a global variable is interacted with, all cells+referencing the global variable are run automatically_.+If you have many UI elements or don't know the elementsyou'll create until runtime, use `marimo.ui.array` and `marimo.ui.dictionary`to create UI elements that wrap other UI elements (`sliders =@@ -185,19 +188,13 @@ To reload modules, use[`importlib.reload()`](https://docs.python.org/3/library/importlib.html#importlib.reload):```+import mymoduleimport importlibimportlib.reload(mymodule)```-Running this cell will reload `mymodule` with your new edits, but-won't automatically run cells using `mymodule`. If you want cells using-`mymodule` to re-run, use this instead:--```-import importlib-import mymodule-importlib.reload(mymodule)-```+Running this cell will reload `mymodule` with your new edits and automatically+re-run any cells using `mymodule`.<a name="faq-notebook-app" ></a>**What's the difference between a marimo notebook and a marimo app?**diff --git a/docs/index.md b/docs/index.mdindex 25b6723b0d..1aa591fa0d 100644--- a/docs/index.md+++ b/docs/index.md@@ -69,9 +69,10 @@ notebooks</a>.getting_started/indexguides/indexapi/index- integrations/index- examples+ recipesfaq+ examples+ integrations/indexcommunity```diff --git a/docs/recipes.md b/docs/recipes.mdnew file mode 100644index 0000000000..a0668b1465--- /dev/null+++ b/docs/recipes.md@@ -0,0 +1,416 @@+# Recipes++This page includes code snippets or "**recipes**" for a variety of common tasks.+Use them as building blocks or examples when making your own notebooks.++In these recipes, **each code block represents a cell**.++## Control Flow++### Show an output conditionally++**Use cases.** Hide an output until a condition is met (_e.g._, until algorithm+parameters are valid), or show different outputs depending on the value of a UI+element or some other Python object++**Recipe.**++1. Use an `if` expression to choose which output to show.++```python+# condition is a boolean, True of False+condition = True+"condition is True" if condition else None+```++### Run a cell on a timer++**Use cases.**++- Load new data periodically, and show updated plots or other outputs. For+ example, in a dashboard monitoring a training run, experiment trial,+ real-time weather data, ...+- Run a job periodically++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Create a [`mo.ui.refresh`](api/inputs/refresh.md#marimo.ui.refresh) timer that fires once a second:++```python+refresh = mo.ui.refresh(default_interval="1s")+# This outputs a timer that fires once a second+refresh+```++3. Reference the timer by name to make this cell run once a second++```python+import random++# This cell will run once a second!+refresh++mo.md("#" + "🍃" * random.randint(1, 10))+```++### Require form submission before sending UI value++**Use cases.** UI elements automatically send their values to the Python when+they are interacted with, and run all cells referencing the elements. This+makes marimo notebooks responsive, but it can be an issue when the+downstream cells are expensive, or when the input (such as a text box)+needs to be filled out completely before it is considered valid. Forms+let you gate submission of UI element values on manual confirmation, via a+button press.++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Create a submittable form.++```python+form = mo.text(label="Your name").form()+form+```++3. Get the value of the form.++```python+form.value+```++### Stop execution of a cell and its descendants++**Use cases.** For example, don't run a cell or its descendants if a form is+unsubmitted.++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Create a submittable form.++```python+form = mo.text(label="Your name").form()+form+```++3. Use [`mo.stop`](api/control_flow.md#marimo.stop) to stop execution when+the form is unsubmitted.++```python+mo.stop(form.value is None, mo.md("Submit the form to continue"))++mo.md(f"Hello, {form.value}!")+```+++## Grouping UI elements together+### Create an array of UI elements++**Use cases.** In order to synchronize UI elements between the frontend and+backend (Python), marimo requires you to+[assign UI elements to global variables](guides/interactivity.md).+But sometimes you don't know the number of elements to make until runtime:+for example, maybe you want o make a list of sliders, and the number of sliders+to make depends on the value of some other UI element.++You might be tempted to create a Python list of UI elements,+such as `l = [mo.ui.slider(1, 10) for i in range(number.value)]`: _however,+this won't work, because the sliders are not bound to global variables_.++For such cases, marimo provides the "higher-order" UI element+[`mo.ui.array`](api/inputs/array.md#marimo.ui.array), which lets you make+a new UI element out of a list of UI elements:+`l = mo.ui.array([mo.ui.slider(1, 10) for i in range(number.value)])`.+The value of an `array` element is a list of the values of the elements+it wraps (in this case, a list of the slider values). Any time you interact+with any of the UI elements in the array, all cells referencing the array+by name (in this case, "`l`") will run automatically.++**Recipe.**++1. Import packages.++```python+import marimo as mo+```++2. Use [`mo.ui.array`](api/inputs/array.md#marimo.ui.array) to group together+ many UI elements into a list.++```python+import random++# instead of random.randint, in your notebook you'd use the value of+# an upstream UI element or other Python object+array = mo.ui.array([mo.ui.text() for i in range(random.randint(1, 10))])+array+```++3. Get the value of the UI elements using `array.value`++```python+array.value+```++### Create a dictionary of UI elements++**Use cases.** Same as for creating an array of UI elements, but lets you+name each of the wrapped elements with a string key.++**Recipe.**++1. Import packages.++```python+import marimo as mo+```++2. Use [`mo.ui.dictionary`](api/inputs/dictionary.md#marimo.ui.dictionary) to+ group together many UI elements into a list.++```python+import random++# instead of random.randint, in your notebook you'd use the value of+# an upstream UI element or other Python object+dictionary = mo.ui.dictionary({str(i): mo.ui.text() for i in range(random.randint(1, 10))})+dictionary+```++3. Get the value of the UI elements using `dictionary.value`++```python+dictionary.value+```++### Create a form with multiple UI elements++**Use cases.** Combine multiple UI elements into a form so that submission+of the form sends all its elements to Python.++**Recipe.**++1. Import packages.++```python+import marimo as mo+```++2. Use [`mo.ui.form`](api/inputs/form.md#marimo.ui.form) and+[`Html.batch`](api/html.md#marimo.Html.batch) to create a form with+multiple elements.++```python+form = mo.md(+ r"""+ Choose your algorithm parameters:++ - $\epsilon$: {epsilon}+ - $\delta$: {delta}+ """+).batch(epsilon=mo.ui.slider(0.1, 1, step=0.1), delta=mo.ui.number(1, 10)).form()+form+```++3. Get the submitted form value.++```python+form.value+```+++## Working with buttons++### Create a counter button++**Use cases.** A counter button, i.e. a button that counts the number of times+it has been clicked, is a helpful building block for reacting to button clicks+(see other recipes in this section).++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Use [`mo.ui.button`](api/inputs/button.md#marimo.ui.button) and its+ `on_click` argument to create a counter button.++```python+# Initialize the button value to 0, increment it on every click+button = mo.ui.button(value=0, on_click=lambda count: count + 1)+button+```++3. Get the button value++```python+button.value+```++### Create a toggle button++**Use cases.** Toggle between two states using a button with a button+that toggles between `True` and `False`. (Tip: you can also just use+[`mo.ui.switch`](api/inputs/switch.md#marimo.ui.switch).)++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Use [`mo.ui.button`](api/inputs/button.md#marimo.ui.button) and its+ `on_click` argument to create a toggle button.++```python+# Initialize the button value to False, flip its value on every click.+button = mo.ui.button(value=False, on_click=lambda value: not value)+button+```++3. Toggle between two outputs using the button value.++```python+mo.md("True!") if button.value else mo.md("False!")+```++### Re-run a cell when a buton is pressed++**Use cases.** For example, you have a cell showing a random sample of data,+and you want to resample on button press.+++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Create a button without a value, to function as a _trigger_.++```python+button = mo.ui.button()+button+```++3. Reference the button in another cell.++```python+# the button acts as a trigger: every time it is clicked, this cell is run+button++# Replace with your custom lgic+import random+random.randint(0, 100)+```++### Run a cell when a button is pressed, but not before++**Use cases.** Wait for confirmation before executing downstream cells+(similar to a form).+++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Create a counter button.++```python+button = mo.ui.button(value=0, on_click=lambda count: count + 1)+button+```++3. Only execute when the count is greater than 0.++```python+# Don't run this cell if the button hasn't been clicked, using mo.stop.+# Alternatively, use an if expression.+mo.stop(button.value == 0)++mo.md(f"The button was clicked {button.value} times")+```+++### Reveal an output when a button is pressed++**Use cases.** Incrementally reveal a user interface.++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Create a counter button.++```python+button = mo.ui.button(value=0, on_click=lambda count: count + 1)+button+```++3. Show an output after the button is clicked.++```python+mo.md("#" + "🍃" * button.value) if button.value > 0 else None+```++## Caching++### Cache expensive computations++**Use case.** Because marimo runs cells automatically as code and+UI elements change, it can be helpful to cache expensive intermediate+computations. For example, perhaps your notebook computes t-SNE, UMAP, or PyMDE+embeddings, and exposes their parameters as UI elements. Caching the embeddings+for different configurations of the elements would greatly speed up your notebook.++**Recipe.**++1. Use `functools` to cache function outputs given inputs.++```python+import functools++def compute_predictions(problem_parameters):+ # replace with your own function/parameters+ ...+```++Whenever `compute_predictions` is called with a value of `problem_parameters`+it has not seen, it will compute the predictions and store them in a cache. The+next time it is called with the same parameters, instead of recomputing the+predictions, it will return the previously computed value from the cache.++See our [best practices guide](guides/best_practices) to learn more.diff --git a/marimo/_runtime/control_flow.py b/marimo/_runtime/control_flow.pyindex 85198cfd32..97f40a405a 100644--- a/marimo/_runtime/control_flow.py+++ b/marimo/_runtime/control_flow.py@@ -27,7 +27,7 @@ class MarimoStopError(BaseException):@mddocdef stop(predicate: bool, output: Optional[object] = None) -> None:- """Stops execution of a cell when `predicate` is `False`+ """Stops execution of a cell when `predicate` is `True`When `predicate` is `True`, this function raises a `MarimoStopError`. Ifuncaught, this exception stops execution of the current cell and makes