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.

docs: expensive notebooks (#2945)

Akshay Agrawal1f2d0f8198f1
diff --git a/docs/guides/best_practices/index.md b/docs/guides/best_practices.md
similarity index 68%
rename from docs/guides/best_practices/index.md
rename to docs/guides/best_practices.md
index 79bf03db0e..60216abbb6 100644
--- a/docs/guides/best_practices/index.md
+++ b/docs/guides/best_practices.md
@@ -1,14 +1,6 @@
# Best practices
-```{eval-rst}
-.. toctree::
- :maxdepth: 2
- :hidden:
-
- performance
-```
-
Here are best practices for writing marimo notebooks.
**Use global variables sparingly.** Keep the number of global variables in your
@@ -24,8 +16,24 @@ result in better code.
global namespace with
temporary or intermediate variables, and to avoid code duplication.
+**Use [`mo.stop`](#marimo.stop) to stop execution.** Use [`mo.stop`](#marimo.stop)
+to stop a cell from running when a condition is true; this is helpful
+when working with expensive notebooks. For example, prevent a cell from running
+until a button is clicked using [`mo.ui.run_button`](#marimo.ui.run_button) and
+[`mo.stop`](#marimo.stop).
+
+```{admonition} Expensive notebooks
+:class: caution
+
+For more tips on working with expensive notebooks, see the
+associated [guide](/guides/expensive_notebooks.md).
+```
+
**Use Python modules.** If your notebook gets too long, split complex logic
-into helper Python modules and import them into your notebook.
+into helper Python modules and import them into your notebook. Use marimo's
+built-in [module
+reloading](/guides/configuration/runtime_configuration.md#on-module-change)
+to automatically bring changes from your modules into your notebook.
**Minimize mutations.** marimo does not track mutations to objects. Try to
only mutate an object in the cell that creates it, or create new objects
@@ -69,11 +77,3 @@ extended_list = l + [new_item()]
Write cells whose outputs and behavior are the same
when given the same inputs (references); such cells are called idempotent. This
will help you avoid bugs and cache expensive intermediate computations.
-
-```{admonition} Performance
-:class: tip
-
-For tips on writing
-performant notebooks (e.g., how to cache intermediate outputs), see the
-[performance guide](/guides/best_practices/performance.md).
-```
diff --git a/docs/guides/editor_features/overview.md b/docs/guides/editor_features/overview.md
index b467d5ab95..fa995bdb0f 100644
--- a/docs/guides/editor_features/overview.md
+++ b/docs/guides/editor_features/overview.md
@@ -30,7 +30,7 @@ A non-exhaustive list of settings:
- Code formatting with ruff/black
- [GitHub Copilot](/guides/editor_features/ai_completion.md)
- [LLM coding assistant](/guides/editor_features/ai_completion.md)
-- [Module autoreloading](/guides/reactivity.md#module-change)
+- [Module autoreloading](/guides/configuration/runtime_configuration.md#on-module-change)
### Vim keybindings
diff --git a/docs/guides/best_practices/performance.md b/docs/guides/expensive_notebooks.md
similarity index 59%
rename from docs/guides/best_practices/performance.md
rename to docs/guides/expensive_notebooks.md
index 83a2e21aea..78a7cc27b0 100644
--- a/docs/guides/best_practices/performance.md
+++ b/docs/guides/expensive_notebooks.md
@@ -1,10 +1,68 @@
-# Performance
+# Expensive notebooks
-## Disable autorun
+marimo provides tools to control when cells run. Use these tools to
+prevent expensive cells, which may call APIs or take a long time to run, from
+accidentally running.
-For expensive notebooks, you can [disable automatic execution](/guides/reactivity.md#runtime-configuration).
+## Stop execution with `mo.stop`
-## Cache computations with `@mo.cache`
+Use [`mo.stop`](#marimo.stop) to stop a cell from executing if a condition
+is met:
+
+```
+# if condition is True, the cell will stop executing after mo.stop() returns
+mo.stop(condition)
+# this won't be called if condition is True
+expensive_function_call()
+```
+
+Use [`mo.stop()`](#marimo.stop) in conjunction with
+[`mo.ui.run_button()`](#marimo.ui.run_button) to require a button press for
+expensive cells:
+
+```{eval-rst}
+.. marimo-embed::
+ :size: medium
+
+ @app.cell
+ def __():
+ run_button = mo.ui.run_button()
+ run_button
+ return
+
+ @app.cell
+ def __():
+ mo.stop(not run_button.value, mo.md("Click 👆 to run this cell"))
+ mo.md("You clicked the button! 🎉")
+ return
+```
+
+## Configure how marimo runs cells
+
+### Disabling cell autorun
+
+If you habitually work with very expensive notebooks, you can
+[disable automatic
+execution](/guides/configuration/runtime_configuration.md#on-cell-change). When
+automatic execution is disabled, when you run a cell, marimo
+marks dependent cells as stale instead of running them automatically.
+
+### Disabling autorun on startup
+
+marimo autoruns notebooks on startup, with `marimo edit notebook.py` behaving
+analogously to `python notebook.py`. This can also be disabled through the
+[notebook settings](/guides/configuration/runtime_configuration.md#on-startup).
+
+### Disable individual cells
+
+marimo lets you temporarily disable cells from automatically running. This is
+helpful when you want to edit one part of a notebook without triggering
+execution of other parts. See the
+[reactivity guide](/guides/reactivity.md#disabling-cells) for more info.
+
+## Caching
+
+### Cache computations with `@mo.cache`
Use [`mo.cache`](#marimo.cache) to cache the return values of
expensive functions, based on their arguments:
@@ -45,11 +103,11 @@ the overhead is negligible. For performance critical code, where the decorated
function will be called in a tight loop, prefer `functools.cache`.
:::
-## Save/load from disk with `mo.persistent_cache`
+### Save and load from disk with `mo.persistent_cache`
-Use `mo.persistent_cache` to cache variables to disk. The next time your
-run your notebook, the cached variables will be loaded from disk instead of
-being recomputed, letting you pick up where you left off.
+Use [`mo.persistent_cache`](#marimo.persistent_cache) to cache variables to
+disk. The next time your run your notebook, the cached variables will be loaded
+from disk instead of being recomputed, letting you pick up where you left off.
Reserve this for expensive computations that you would like to persist across
notebook restarts. Cached outputs are automatically saved to `__marimo__/cache`.
@@ -72,16 +130,10 @@ is not stale, meaning its code hasn't changed and neither have its ancestors.
On cache hit the code block won't execute and instead variables will be loaded
into memory.
-## Disable expensive cells
-
-marimo lets you temporarily disable cells from automatically running. This is
-helpful when you want to edit one part of a notebook without triggering
-execution of other parts. See the
-[reactivity guide](/guides/reactivity.md#disabling-cells) for more info.
-
-## Lazy-load expensive elements or computations
+## Lazy-load expensive UIs
-You can lazily render UI elements that are expensive to compute using `marimo.lazy`.
+Lazily render UI elements that are expensive to compute using
+`marimo.lazy`.
For example,
@@ -111,4 +163,8 @@ accordion = mo.ui.accordion({
})
```
-In this example, we pass a function to `mo.lazy` instead of a component. This function will only be called when the user opens the accordion. In this way, `expensive_component` lazily computed and we only query the database when the user needs to see the data. This can be useful when the data is expensive to compute and the user may not need to see it immediately.
+In this example, we pass a function to `mo.lazy` instead of a component. This
+function will only be called when the user opens the accordion. In this way,
+`expensive_component` lazily computed and we only query the database when the
+user needs to see the data. This can be useful when the data is expensive to
+compute and the user may not need to see it immediately.
diff --git a/docs/guides/index.md b/docs/guides/index.md
index e9119a6f01..93c8363432 100644
--- a/docs/guides/index.md
+++ b/docs/guides/index.md
@@ -9,20 +9,22 @@
reactivity
interactivity
outputs
+ expensive_notebooks
working_with_data/index
editor_features/index
configuration/index
apps
scripts
- best_practices/index
coming_from/index
integrating_with_marimo/index
state
wasm
exporting
deploying/index
+ best_practices
troubleshooting
```
+
These guides cover marimo's core concepts.
```{admonition} Learn by doing!
@@ -32,23 +34,23 @@ Prefer a hands-on learning experience? marimo comes packaged with interactive
tutorials that you can launch with `marimo tutorial` at the command line.
```
-
| Guide | Description |
| :----------------------------------- | :----------------------------------------------------------- |
| {doc}`overview` | An overview of basic concepts |
-| {doc}`reactivity` | How reactive execution works |
+| {doc}`reactivity` | How marimo runs cells |
| {doc}`interactivity` | Using interactive UI elements |
| {doc}`outputs` | Creating markdown, plots, and other visual outputs |
+| {doc}`expensive_notebooks` | Tips for working with expensive notebooks |
| {doc}`working_with_data/index` | Using SQL cells, no-code dataframe tools, and reactive plots |
| {doc}`editor_features/index` | View variables, dataframe schemas, docstrings, and more |
| {doc}`configuration/index` | Configure various settings |
| {doc}`apps` | Running notebooks as apps |
| {doc}`scripts` | Running notebooks as scripts |
-| {doc}`best_practices/index` | Best practices to help you get the most out of marimo |
| {doc}`coming_from/index` | Transitioning from Jupyter and other tools |
| {doc}`integrating_with_marimo/index` | Rich displays of objects, custom UI plugins |
| {doc}`state` | Advanced: mutable reactive state |
| {doc}`wasm` | Create notebooks in our online playground |
| {doc}`exporting` | Exporting notebooks to HTML and flat scripts |
| {doc}`deploying/index` | Deploying marimo notebooks and apps |
+| {doc}`best_practices` | Best practices to help you get the most out of marimo |
| {doc}`troubleshooting` | Troubleshooting notebooks |
diff --git a/docs/guides/interactivity.md b/docs/guides/interactivity.md
index 4ec7a90077..d44b07a246 100644
--- a/docs/guides/interactivity.md
+++ b/docs/guides/interactivity.md
@@ -1,4 +1,4 @@
-# Interactivity
+# Interactive elements
One of marimo's most powerful features is its first-class support for
interactive, stateful user interface (UI) elements, or "widgets": create them using
@@ -19,7 +19,7 @@ variable, its value is sent back to Python. A single rule determines what
happens next:
```{admonition} Interaction rule
-:class: tip
+:class: important
When a UI element assigned to a global variable is interacted with, marimo
automatically runs all cells that reference the variable (but don't define it).
diff --git a/docs/guides/outputs.md b/docs/guides/outputs.md
index 3e951abafe..655b81de06 100644
--- a/docs/guides/outputs.md
+++ b/docs/guides/outputs.md
@@ -1,4 +1,4 @@
-# Outputs
+# Cell outputs
The last expression of a cell is its visual output, rendered above the cell.
Outputs are included in the "app" or read-only view of the notebook. marimo
diff --git a/docs/guides/overview.md b/docs/guides/overview.md
index dde912700a..1cc97667e9 100644
--- a/docs/guides/overview.md
+++ b/docs/guides/overview.md
@@ -27,13 +27,15 @@ variables defined by that cell._ This is reactive execution.
</figure>
</div>
-```{admonition} Lazy evaluation
-:class: tip
+```{admonition} Working with expensive notebooks
+:class: important
+
+If you don't want cells to run automatically, the [runtime can be
+configured](/guides/configuration/runtime_configuration.md) to be lazy, only
+running cells when you ask for them to be run and marking affected cells as
+stale. **See our guide on working with [expensive
+notebooks](/guides/expensive_notebooks.md) for more tips.**
-If you don't want cells to run automatically, the runtime can be
-configured to be lazy, only running cells when you ask for them to be run and
-marking affected cells as stale. Learn more in the
-[runtime configuration guide](/guides/configuration/runtime_configuration.md)
```
**Execution order.**
@@ -96,8 +98,8 @@ import marimo as mo
marimo visualizes the last expression of each cell as its **output**. Outputs
can be any Python value, including markdown and interactive elements created
with the marimo library, _e.g._, `mo.md(...)`, `mo.ui.slider(...)`.
-You can even interpolate Python values into markdown and other marimo elements
-to build rich composite outputs.
+You can even interpolate Python values into markdown (using `mo.md(f"...")`) and
+other marimo elements to build rich composite outputs:
<div align="center">
<figure>
diff --git a/docs/guides/reactivity.md b/docs/guides/reactivity.md
index c99da6ea21..79fec0f7e1 100644
--- a/docs/guides/reactivity.md
+++ b/docs/guides/reactivity.md
@@ -1,4 +1,4 @@
-# Reactivity
+# Reactive execution
Every marimo notebook is a directed acyclic graph (DAG) that models how data
flows across blocks of Python code, i.e., cells.
@@ -10,19 +10,21 @@ the page.
Reactive execution is based on a single rule:
```{admonition} Runtime Rule
-:class: tip
+:class: important
When a cell is run, marimo automatically runs all other cells that
**reference** any of the global variables it **defines**.
```
-```{admonition} Lazy evaluation
-:class: note
+```{admonition} Working with expensive notebooks
+:class: tip
-The runtime can be configured to be lazy, only running cells when you ask for
-them to be run and marking affected cells as stale, instead of automatically
-running them. Learn more in the
-[runtime configuration guide](/guides/configuration/runtime_configuration.md)
+marimo gives you tools that make it easy to work with expensive notebooks. For
+example, the [runtime can be
+configured](#/guides/configuration/runtime_configuration.md) to be lazy, only
+running cells when you ask for them to be run and marking affected cells as
+stale instead of auto-running them. **See our guide on working with [expensive
+notebooks](/guides/expensive_notebooks.md) for more tips.**
```
## References and definitions
@@ -37,8 +39,8 @@ dependencies. marimo creates this graph by statically analyzing each cell
```{admonition} Global variables
:class: tip
-A variable can refer to any Python object. In particular, functions,
-classes, and imported names are all variables.
+A variable can refer to any Python object. Functions, classes, and imported
+names are all variables.
```
There is an edge from one cell to another if the latter cell references any
@@ -52,7 +54,7 @@ To make sure your notebook is DAG, marimo requires that every global
variable be defined by only one cell.
```{admonition} Local variables
-:class: note
+:class: important
Variables prefixed with an underscore are local to a cell (_.e.g._, `_x`). You
can use this in a pinch to fix multiple definition errors, but try instead to
@@ -82,7 +84,7 @@ many others
[[1]](https://austinhenley.com/pubs/Chattopadhyay2020CHI_NotebookPainpoints.pdf)
[[2]](https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit#slide=id.g362da58057_0_1).
-**marimo eliminates the problem of hidden state**: running
+**marimo eliminates hidden state**: running
a cell automatically refreshes downstream outputs, and _deleting a cell
deletes its global variables from program memory_.
diff --git a/marimo/_config/packages.py b/marimo/_config/packages.py
index 178a44248c..93ae956534 100644
--- a/marimo/_config/packages.py
+++ b/marimo/_config/packages.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
import os
diff --git a/marimo/_output/formatters/repr_formatters.py b/marimo/_output/formatters/repr_formatters.py
index 29095cac02..f6a2d86ba0 100644
--- a/marimo/_output/formatters/repr_formatters.py
+++ b/marimo/_output/formatters/repr_formatters.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
from typing import Any, Callable, Optional, Tuple
diff --git a/marimo/_utils/methods.py b/marimo/_utils/methods.py
index 17a44277cb..3d859877bc 100644
--- a/marimo/_utils/methods.py
+++ b/marimo/_utils/methods.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
import inspect