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: google style docs (#3217)
Myles Scolnicke614b60e4179
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 221992407c..0992287805 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -186,6 +186,16 @@ class CellImpl:@propertydef runtime_state(self) -> Optional[RuntimeStateType]:+ """Gets the current runtime state of the cell.++ Returns:+ Optional[RuntimeStateType]: The current state, one of:+ - "idle": cell has run with latest inputs+ - "queued": cell is queued to run+ - "running": cell is running+ - "disabled-transitively": cell is disabled because a parent is disabled+ - None: state not set+ """return self._status.state@property@@ -194,7 +204,11 @@ class CellImpl:@propertydef sqls(self) -> list[str]:- """Return a list of SQL statements for this cell."""+ """Returns parsed SQL statements from this cell.++ Returns:+ list[str]: List of SQL statement strings parsed from the cell code.+ """if self._sqls.parsed is not None:return self._sqls.parsed@@ -257,7 +271,12 @@ class CellImpl:def set_runtime_state(self, status: RuntimeStateType, stream: Stream | None = None) -> None:- """Set execution status and broadcast to frontends."""+ """Sets the cell's execution status and broadcasts to frontends.++ Args:+ status (RuntimeStateType): New runtime state to set+ stream (Stream | None, optional): Stream to broadcast on. Defaults to None.+ """from marimo._messaging.ops import CellOpfrom marimo._runtime.context import (ContextNotInitializedError,@@ -405,103 +424,104 @@ class Cell:tuple[Any, Mapping[str, Any]]| Awaitable[tuple[Any, Mapping[str, Any]]]):- """Run this cell and return its visual output and definitions+ """+ Run this cell and return its visual output and definitions.Use this method to run **named cells** and retrieve their output and- definitions.-- This lets you use reuse cells defined in one notebook in another+ definitions. This lets you reuse cells defined in one notebook in anothernotebook or Python file. It also makes it possible to write and executeunit tests for notebook cells using a test framework like `pytest`.- **Example.** marimo cells can be given names either through the- editor cell menu or by manually changing the function name in the- notebook file. For example, consider a notebook `notebook.py`:-- ```python- import marimo+ Examples:+ marimo cells can be given names either through the editor cell menu+ or by manually changing the function name in the notebook file. For+ example, consider a notebook `notebook.py`:- app = marimo.App()+ ```python+ import marimo+ app = marimo.App()- @app.cell- def __():- import marimo as mo- return (mo,)+ @app.cell+ def __():+ import marimo as mo+ return (mo,)- @app.cell- def __():- x = 0- y = 1- return (x, y)+ @app.cell+ def __():+ x = 0+ y = 1+ return (x, y)- @app.cell- def add(mo, x, y):- z = x + y- mo.md(f"The value of z is {z}")- return (z,)+ @app.cell+ def add(mo, x, y):+ z = x + y+ mo.md(f"The value of z is {z}")+ return (z,)- if __name__ == "__main__":- app.run()- ```- To reuse the `add` cell in another notebook, you'd simply write+ if __name__ == "__main__":+ app.run()+ ```- ```python- from notebook import add+ To reuse the `add` cell in another notebook, you'd simply write:- # `output` is the markdown rendered by `add`- # defs["z"] == `1`- output, defs = add.run()- ```+ ```python+ from notebook import add- When `run` is called without arguments, it automatically computes the- values that the cell depends on (in this case, `mo`, `x`, and `y`). You- can override these values by providing any subset of them as keyword- arguments. For example,+ # `output` is the markdown rendered by `add`+ # defs["z"] == `1`+ output, defs = add.run()+ ```- ```python- # defs["z"] == 4- output, defs = add.run(x=2, y=2)- ```+ When `run` is called without arguments, it automatically computes+ the values that the cell depends on (in this case, `mo`, `x`, and+ `y`). You can override these values by providing any subset of them+ as keyword arguments. For example,- **Defined UI Elements.** If the cell's `output` has UI elements- that are in `defs`, interacting with the output in the frontend will- trigger reactive execution of cells that reference the `defs` object.- For example, if `output` has a slider defined by the cell, then- scrubbing the slider will cause cells that reference `defs` to run.+ ```python+ # defs["z"] == 4+ output, defs = add.run(x=2, y=2)+ ```- **Async cells.** If this cell is a coroutine function (starting with- `async`), or if any of its ancestors are coroutine functions, then- you'll need to `await` the result: `output, defs = await cell.run()`.- You can check whether the result is an awaitable using:+ Defined UI Elements:+ If the cell's `output` has UI elements that are in `defs`, interacting+ with the output in the frontend will trigger reactive execution of+ cells that reference the `defs` object. For example, if `output` has+ a slider defined by the cell, then scrubbing the slider will cause+ cells that reference `defs` to run.- ```python- from collections.abc import Awaitable-- ret = cell.run()- if isinstance(ret, Awaitable):- output, defs = await ret- else:- output, defs = ret- ```+ Async cells:+ If this cell is a coroutine function (starting with `async`), or if+ any of its ancestors are coroutine functions, then you'll need to+ `await` the result: `output, defs = await cell.run()`. You can check+ whether the result is an awaitable using:- **Arguments**:+ ```python+ from collections.abc import Awaitable- - You may pass values for any of this cell's references as keyword- arguments. marimo will automatically compute values for any refs- that are not provided by executing the parent cells that compute- them.+ ret = cell.run()+ if isinstance(ret, Awaitable):+ output, defs = await ret+ else:+ output, defs = ret+ ```- **Returns**:+ Args:+ **kwargs (Any):+ You may pass values for any of this cell's references as keyword+ arguments. marimo will automatically compute values for any refs+ that are not provided by executing the parent cells that compute+ them.- - a tuple `(output, defs)`, or an awaitable of the same, where `output`- is the cell's last expression and `defs` is a `Mapping` from the- cell's defined names to their values.+ Returns:+ tuple `(output, defs)`, or an awaitable of the same:+ `output` is the cell's last expression and `defs` is a `Mapping`+ from the cell's defined names to their values."""assert self._app is not Noneif self._is_coroutine():diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex a18bec286b..3d762caf43 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -332,21 +332,18 @@ def interactive(figure: Union[Figure, SubFigure, Axes]) -> Html:The interactive viewer allows you to pan, zoom, and see plot coordinateson mouse hover.- **Example**:-- ```python- plt.plot([1, 2])- # plt.gcf() gets the current figure- mo.mpl.interactive(plt.gcf())- ```-- **Args**:-- - figure: a matplotlib `Figure` or `Axes` object-- **Returns**:-- - An interactive matplotlib figure as an `Html` object+ Example:+ ```python+ plt.plot([1, 2])+ # plt.gcf() gets the current figure+ mo.mpl.interactive(plt.gcf())+ ```++ Args:+ figure (matplotlib Figure or Axes): A matplotlib `Figure` or `Axes` object.++ Returns:+ Html: An interactive matplotlib figure as an `Html` object."""# We can't support interactive plots in Pyodide# since they require a WebSocket connectiondiff --git a/marimo/_runtime/app_meta.py b/marimo/_runtime/app_meta.pyindex f277593ed3..ff13c52d31 100644--- a/marimo/_runtime/app_meta.py+++ b/marimo/_runtime/app_meta.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom typing import Literal, Optionalfrom marimo._config.config import DEFAULT_CONFIG+from marimo._output.rich_help import mddocfrom marimo._runtime.context.types import (ContextNotInitializedError,get_context,@@ -11,9 +12,9 @@ from marimo._runtime.context.types import (from marimo._runtime.context.utils import get_mode+@mddocclass AppMeta:- """- Metadata about the app.+ """Metadata about the app.This class provides access to runtime metadata about a marimo app, such asits display theme and execution mode.@@ -23,25 +24,21 @@ class AppMeta:def theme(self) -> str:"""The display theme of the app.- Returns either "light" or "dark". If the user's configuration is set to- "system", currently returns "light".-- **Examples**:-- Get the current theme and conditionally set a plotting library's theme:-- ```python- import altair as alt+ Returns:+ str: Either "light" or "dark". If the user's configuration is set to+ "system", currently returns "light".- # Enable dark theme for Altair when marimo is in dark mode- alt.themes.enable(- "dark" if mo.app_meta().theme == "dark" else "default"- )- ```+ Examples:+ Get the current theme and conditionally set a plotting library's theme:- **Returns**:+ ```python+ import altair as alt- - "light" or "dark", indicating the app's display theme+ # Enable dark theme for Altair when marimo is in dark mode+ alt.themes.enable(+ "dark" if mo.app_meta().theme == "dark" else "default"+ )+ ```"""try:context = get_context()@@ -57,22 +54,21 @@ class AppMeta:@propertydef mode(self) -> Optional[Literal["edit", "run", "script"]]:- """The execution mode of the app.-- **Examples**:-- Show content only in edit mode:+ """+ The execution mode of the app.- ```python- # Only show this content when editing the notebook- mo.md("# Developer Notes") if mo.app_meta().mode == "edit" else None- ```+ Examples:+ Show content only in edit mode:- **Returns**:+ ```python+ # Only show this content when editing the notebook+ mo.md("# Developer Notes") if mo.app_meta().mode == "edit" else None+ ```- - "edit": The notebook is being edited in the marimo editor- - "run": The notebook is being run as an app- - "script": The notebook is being run as a script- - None: The mode could not be determined+ Returns:+ - "edit": The notebook is being edited in the marimo editor+ - "run": The notebook is being run as an app+ - "script": The notebook is being run as a script+ - None: The mode could not be determined"""return get_mode()diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex b734bee692..3584be4a61 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -149,9 +149,8 @@ LOGGER = _loggers.marimo_logger()def defs() -> tuple[str, ...]:"""Get the definitions of the currently executing cell.- **Returns**:-- - tuple of the currently executing cell's defs.+ Returns:+ tuple[str, ...]: A tuple of the currently executing cell's defs."""try:ctx = get_context()@@ -172,9 +171,8 @@ def defs() -> tuple[str, ...]:def refs() -> tuple[str, ...]:"""Get the references of the currently executing cell.- **Returns**:-- - tuple of the currently executing cell's refs.+ Returns:+ tuple[str, ...]: A tuple of the currently executing cell's refs."""try:ctx = get_context()@@ -202,39 +200,37 @@ def refs() -> tuple[str, ...]:def query_params() -> QueryParams:"""Get the query parameters of a marimo app.- **Examples**:-- Keep the text input in sync with the URL query parameters.-- ```python3- # In it's own cell- query_params = mo.query_params()+ Examples:+ Keep the text input in sync with the URL query parameters:- # In another cell- search = mo.ui.text(- value=query_params["search"] or "",- on_change=lambda value: query_params.set("search", value),- )- search- ```+ ```python3+ # In it's own cell+ query_params = mo.query_params()- You can also set the query parameters reactively:+ # In another cell+ search = mo.ui.text(+ value=query_params["search"] or "",+ on_change=lambda value: query_params.set("search", value),+ )+ search+ ```- ```python3- toggle = mo.ui.switch(label="Toggle me")- toggle+ You can also set the query parameters reactively:- # In another cell- query_params["is_enabled"] = toggle.value- ```+ ```python3+ toggle = mo.ui.switch(label="Toggle me")+ toggle- **Returns**:+ # In another cell+ query_params["is_enabled"] = toggle.value+ ```- - A `QueryParams` object containing the query parameters.- You can directly interact with this object like a dictionary.- If you mutate this object, changes will be persisted to the frontend- query parameters and any other cells referencing the query parameters- will automatically re-run.+ Returns:+ QueryParams: A QueryParams object containing the query parameters.+ You can directly interact with this object like a dictionary.+ If you mutate this object, changes will be persisted to the frontend+ query parameters and any other cells referencing the query parameters+ will automatically re-run."""return get_context().query_params@@ -246,27 +242,25 @@ def app_meta() -> AppMeta:The `AppMeta` class provides access to runtime metadata about a marimo app,such as its display theme and execution mode.- **Examples**:-- Get the current theme and conditionally set a plotting library's theme:+ Examples:+ Get the current theme and conditionally set a plotting library's theme:- ```python- import altair as alt+ ```python+ import altair as alt- # Enable dark theme for Altair when marimo is in dark mode- alt.themes.enable("dark" if mo.app_meta().theme == "dark" else "default")- ```-- Show content only in edit mode:+ # Enable dark theme for Altair when marimo is in dark mode+ alt.themes.enable("dark" if mo.app_meta().theme == "dark" else "default")+ ```- ```python- # Only show this content when editing the notebook- mo.md("# Developer Notes") if mo.app_meta().mode == "edit" else None- ```+ Show content only in edit mode:- **Returns**:+ ```python+ # Only show this content when editing the notebook+ mo.md("# Developer Notes") if mo.app_meta().mode == "edit" else None+ ```- - An `AppMeta` object containing the app's metadata.+ Returns:+ AppMeta: An AppMeta object containing the app's metadata."""return AppMeta()@@ -275,9 +269,8 @@ def app_meta() -> AppMeta:def cli_args() -> CLIArgs:"""Get the command line arguments of a marimo notebook.- **Examples**:-- `marimo edit notebook.py -- -size 10`+ Examples:+ `marimo edit notebook.py -- -size 10````python3# Access the command line arguments@@ -287,10 +280,9 @@ def cli_args() -> CLIArgs:print(i)```- **Returns**:-- - A dictionary containing the command line arguments.- This dictionary is read-only and cannot be mutated.+ Returns:+ CLIArgs: A dictionary containing the command line arguments.+ This dictionary is read-only and cannot be mutated."""return get_context().cli_args@@ -299,21 +291,19 @@ def cli_args() -> CLIArgs:def notebook_dir() -> pathlib.Path | None:"""Get the directory of the currently executing notebook.- **Returns**:-- - A `pathlib.Path` object representing the directory of the current- notebook, or `None` if the notebook's directory cannot be determined.-- **Examples**:+ Returns:+ pathlib.Path | None: A pathlib.Path object representing the directory of the current+ notebook, or None if the notebook's directory cannot be determined.- ```python- data_file = mo.notebook_dir() / "data" / "example.csv"- # Use the directory to read a file- if data_file.exists():- print(f"Found data file: {data_file}")- else:- print("No data file found")- ```+ Examples:+ ```python+ data_file = mo.notebook_dir() / "data" / "example.csv"+ # Use the directory to read a file+ if data_file.exists():+ print(f"Found data file: {data_file}")+ else:+ print("No data file found")+ ```"""try:ctx = get_context()@@ -328,11 +318,14 @@ def notebook_dir() -> pathlib.Path | None:@dataclasses.dataclassclass CellMetadata:- """CellMetadata+ """CellMetadata class for storing cell metadata.Metadata the kernel needs to persist, even when a cell is removedfrom the graph or when a cell can't be formed from user code due to syntaxerrors.++ Attributes:+ config (CellConfig): Configuration for the cell."""config: CellConfig = dataclasses.field(default_factory=CellConfig)@@ -342,16 +335,16 @@ class Kernel:"""Kernel that manages the dependency graph and its execution.Args:- - cell_configs: initial configuration for each cell- - app_metadata: metadata about the notebook- - user_config: the initial user configuration- - stream: object used to communicate with the server/outside world- - stdout: replacement for sys.stdout- - stderr: replacement for sys.stderr- - stdin: replacement for sys.stdin- - module: module in which to execute code- - enqueue_control_request: callback to enqueue control requests- - debugger_override: a replacement for the built-in Pdb+ cell_configs (dict[CellId_t, CellConfig]): Initial configuration for each cell.+ app_metadata (AppMetadata): Metadata about the notebook.+ user_config (MarimoConfig): The initial user configuration.+ stream (Stream): Object used to communicate with the server/outside world.+ stdout (Stdout | None): Replacement for sys.stdout.+ stderr (Stderr | None): Replacement for sys.stderr.+ stdin (Stdin | None): Replacement for sys.stdin.+ module (ModuleType): Module in which to execute code.+ enqueue_control_request (Callable[[ControlRequest], None]): Callback to enqueue control requests.+ debugger_override (marimo_pdb.MarimoPdb | None): A replacement for the built-in Pdb."""def __init__(@@ -1603,21 +1596,18 @@ class Kernel:return bool(updated_components) or bool(referring_cells)def get_ui_initial_value(self, object_id: str) -> Any:- """Get an initial value for a UIElement, if any+ """Get an initial value for a UIElement, if any.- Initial values are optionally populated during instantiation+ Initial values are optionally populated during instantiation.Args:- ----- object_id: ID of UIElement+ object_id (str): ID of UIElement.Returns:- -------- initial value of UI element, if any+ Any: Initial value of UI element, if any.Raises:- ------- KeyError if object_id not found+ KeyError: If object_id not found."""return self.ui_initializers[object_id]@@ -1631,8 +1621,15 @@ class Kernel:"""Execute a function call.If the function is not found, children contexts are also searched.- Returns a status, payload, and a bool which is True if the function was- found, False otherwise.++ Args:+ request (FunctionCallRequest): The function call request.++ Returns:+ tuple[HumanReadableStatus, JSONType, bool]: A tuple containing:+ - status: Human readable status of the function call+ - payload: The function return value+ - found: True if the function was found, False otherwise"""ctx = get_context()function = ctx.function_registry.get_function(@@ -1845,6 +1842,12 @@ class Kernel:"""Preview a column of a dataset.The dataset is loaded, and the column is displayed in the frontend.++ Args:+ request (PreviewDatasetColumnRequest): The preview request containing:+ - table_name: Name of the table+ - column_name: Name of the column+ - source_type: Type of data source ("duckdb" or "local")"""table_name = request.table_namecolumn_name = request.column_namediff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.pyindex 3714620022..3c7324defe 100644--- a/marimo/_runtime/state.py+++ b/marimo/_runtime/state.py@@ -170,93 +170,74 @@ class SetFunctor(Generic[T]):def state(value: T, allow_self_loops: bool = False) -> tuple[State[T], Callable[[T], None]]:- """Mutable reactive state+ """+ 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+ - a getter function that reads the state value+ - a setter function to set the state's valueWhen you call the setter function and update the state value in one cell,all *other* cells that read any global variables assigned to the getterwill automatically run. By default, the cell that called the setter- function won't be re-run, even if it references the getter; to allow a- state setter to possibly run the caller cell, use the keyword argument+ function won't be re-run, even if it references the getter. To allow a+ state setter to possibly run the caller cell, set the keyword argument`allow_self_loops=True`.- You can use this function in conjunction with `UIElement` `on_change`- handlers to trigger side-effects when an element's value is updated. For- 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]- ```-- **Warning.** Do not store `marimo.ui` elements in state; doing so can- lead to hard-to-diagnose bugs.-- **Args**:-- - `value`: initial value of the state- - `allow_self_loops`: if True, if a cell calls a state setter- and also references its getter, the caller cell will be re-run;- defaults to `False`.---- **Returns**:-- - 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+ You can use this function 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.++ Example usage:+ Create state:+ ```python+ get_count, set_count = mo.state(0)+ ```+ Read the value:+ ```python+ get_count()+ ```+ Update the state:+ ```python+ set_count(1)+ ```+ Update based on current value:+ ```python+ set_count(lambda value: value + 1)+ ```++ 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]+ ```++ Warning:+ Do not store `marimo.ui` elements in state; doing so can cause+ hard-to-diagnose bugs.++ Args:+ value: Initial value of the state.+ allow_self_loops: If True, a cell that calls a state setter and also+ references its getter will be re-run. Defaults to False.++ Returns:+ A tuple of (getter function, setter function). The getter function+ retrieves the state value; the setter function takes a new value or a+ function that updates the current value."""state_instance = State(value, allow_self_loops=allow_self_loops)return state_instance, state_instance._set_valuediff --git a/mkdocs.yml b/mkdocs.ymlindex cf1b405931..47308d81dd 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -1,5 +1,8 @@edit_uri: edit/main/docs/copyright: '© marimo 2024'+watch:+ - docs/+ - marimo/extra:generator: falsesocial: