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
feat: run_button (#1514)
Akshay Agrawal09f01b9b430b
diff --git a/docs/api/inputs/button.md b/docs/api/inputs/button.mdindex 5029d17194..92bc1d2cff 100644--- a/docs/api/inputs/button.md+++ b/docs/api/inputs/button.md@@ -1,5 +1,12 @@# Button+```{admonition} Looking for a submit/run button?+:class: tip++If you're looking for a button to trigger computation on click, consider+using [`mo.ui.run_button`](/api/inputs/run_button.md).+```+```{eval-rst}.. marimo-embed::@app.celldiff --git a/docs/api/inputs/run_button.md b/docs/api/inputs/run_button.mdnew file mode 100644index 0000000000..642cd5e214--- /dev/null+++ b/docs/api/inputs/run_button.md@@ -0,0 +1,31 @@+# Run Button++```{eval-rst}+.. marimo-embed::+ @app.cell+ def __():+ b = mo.ui.run_button()+ b+ return++ @app.cell+ def __():+ s = mo.ui.slider(1, 10)+ s+ return+++ @app.cell+ def __():+ mo.stop(not b.value, "Click `run` to submit the slider's value")++ s.value+ return+```++```{eval-rst}+.. autoclass:: marimo.ui.run_button+ :members:++ .. autoclasstoc:: marimo._plugins.ui._impl.run_button.run_button+```diff --git a/docs/recipes.md b/docs/recipes.mdindex 5e12a3ee5d..e7cc289352 100644--- a/docs/recipes.md+++ b/docs/recipes.md@@ -388,6 +388,36 @@ form.value## Working with buttons+### Create a button that triggers computation when clicked++**Use cases.** To trigger a computation on button click and only on button+click, use [`mo.ui.run_button()`](/api/inputs/run_button.md).++**Recipe.**++1. Import packages++```python+import marimo as mo+```++2. Create a run button++```python+button = mo.ui.run_button()+button+```++3. Run something only if the button has been clicked.++```python+mo.stop(not button.value, "Click 'run' to generate a random number")++import random+random.randint(0, 1000)+```++### Create a counter button**Use cases.** A counter button, i.e. a button that counts the number of timesdiff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex 279f2807e4..a0b0ac9c46 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -27,6 +27,7 @@ __all__ = ["radio","range_slider","refresh",+ "run_button","slider","switch","table",@@ -62,6 +63,7 @@ from marimo._plugins.ui._impl.input import (from marimo._plugins.ui._impl.microphone import microphonefrom marimo._plugins.ui._impl.plotly import plotlyfrom marimo._plugins.ui._impl.refresh import refresh+from marimo._plugins.ui._impl.run_button import run_buttonfrom marimo._plugins.ui._impl.switch import switchfrom marimo._plugins.ui._impl.table import tablefrom marimo._plugins.ui._impl.tabs import tabsdiff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex 93089debb3..95f705d082 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -379,6 +379,10 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):if self._on_change is not None:self._on_change(self._value)+ def _on_update_completion(self) -> None:+ """Callback to run after the kernel has processed a value update."""+ return+def _clone(self) -> UIElement[S, T]:"""Clone a UIElement, returning one with a different iddiff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex 25c751f329..ccf3fbe012 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -990,6 +990,7 @@ class button(UIElement[Any, Any]):) -> None:self._on_click = (lambda _: value) if on_click is None else on_clickself._initial_value = value+ # This should be kept in sync with mo.ui.run_button()super().__init__(component_name=button._name,# frontend's value is always a counterdiff --git a/marimo/_plugins/ui/_impl/run_button.py b/marimo/_plugins/ui/_impl/run_button.pynew file mode 100644index 0000000000..c746cffd61--- /dev/null+++ b/marimo/_plugins/ui/_impl/run_button.py@@ -0,0 +1,116 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any, Callable, Final, Literal, Optional++from marimo._output.rich_help import mddoc+from marimo._plugins.ui._core.ui_element import UIElement+from marimo._plugins.ui._impl.input import button+from marimo._runtime.context.types import ContextNotInitializedError+++@mddoc+class run_button(UIElement[Any, Any]):+ """+ A button that can be used to trigger computation.++ **Example.**++ ```python+ # a button that when clicked will have its value set to True;+ # any cells referencing that button will automatically run.+ button = mo.ui.run_button()+ button+ ```++ ```python+ slider = mo.ui.slider(1, 10)+ slider+ ```++ ```python+ # if the button hasn't been clicked, don't run.+ mo.stop(not button.value)++ slider.value+ ```++ When clicked, `run_button`'s value is set to `True`, and any cells+ referencing it are run. After those cells are run, `run_button`'s+ value will automatically be set back to `False` as long as automatic+ execution is enabled.++ **Attributes.**++ - `value`: the value of the button; `True` when clicked, and reset to+ `False` after cells referencing the button finish running (when+ automatic execution is enabled).++ **Initialization Args.**++ - `kind`: 'neutral', 'success', 'warn', or 'danger'+ - `disabled`: whether the button is disabled+ - `tooltip`: a tooltip to display for the button+ - `label`: text label for the element+ - `on_change`: optional callback to run when this element's value changes+ - `full_width`: whether the input should take up the full width of its+ container+ """++ # We reuse the button plugin on the frontend, UI/logic are the same+ _name: Final[str] = button._name++ def __init__(+ self,+ kind: Literal["neutral", "success", "warn", "danger"] = "neutral",+ disabled: bool = False,+ tooltip: Optional[str] = None,+ *,+ label: str = "click to run",+ on_change: Optional[Callable[[Any], None]] = None,+ full_width: bool = False,+ ) -> None:+ self._initial_value = False+ super().__init__(+ component_name=button._name,+ # frontend's value is a counter+ initial_value=0,+ label=label,+ args={+ "kind": kind,+ "disabled": disabled,+ "tooltip": tooltip,+ "full-width": full_width,+ },+ on_change=on_change,+ )++ def _convert_value(self, value: Any) -> Any:+ if value == 0:+ # frontend's value == 0 only during initialization; first value+ # frontend will send is 1+ return False+ else:+ return True++ def _on_update_completion(self) -> None:+ from marimo._runtime.context import get_context+ from marimo._runtime.context.kernel_context import KernelRuntimeContext++ try:+ ctx = get_context()+ except ContextNotInitializedError:+ self._value = False+ return++ if isinstance(ctx, KernelRuntimeContext) and ctx.lazy:+ # Resetting to False in lazy kernels makes the button pointless,+ # since its value hasn't been read by downstream cells on update+ # completion.+ #+ # The right thing to do would be to somehow set to False after+ # all cells that were marked stale because of the update were run,+ # but that's too complicated.+ return+ else:+ self._value = Falsediff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.pyindex 208c0544ac..6b84e1bd0a 100644--- a/marimo/_runtime/context/kernel_context.py+++ b/marimo/_runtime/context/kernel_context.py@@ -43,6 +43,10 @@ class KernelRuntimeContext(RuntimeContext):def execution_context(self) -> ExecutionContext | None:return self._kernel.execution_context+ @property+ def lazy(self) -> bool:+ return self._kernel.lazy()+@propertydef cell_id(self) -> Optional[CellId_t]:"""Get the cell id of the currently executing cell, if any."""diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 14487b2f2a..8c2ceadf53 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -74,9 +74,7 @@ from marimo._runtime.packages.utils import is_python_isolatedfrom marimo._runtime.params import CLIArgs, QueryParamsfrom marimo._runtime.redirect_streams import redirect_streamsfrom marimo._runtime.reload.autoreload import ModuleReloader-from marimo._runtime.reload.module_watcher import (- ModuleWatcher,-)+from marimo._runtime.reload.module_watcher import ModuleWatcherfrom marimo._runtime.requests import (AppMetadata,CompletionRequest,@@ -114,6 +112,8 @@ from marimo._utils.typed_connection import TypedConnectionif TYPE_CHECKING:from collections.abc import Iterable, Sequence+ from marimo._plugins.ui._core.ui_element import UIElement+LOGGER = _loggers.marimo_logger()@@ -998,6 +998,8 @@ class Kernel:Runs cells that reference the UI element by name."""+ updated_components: list[UIElement[Any, Any]] = []+# Resolve lenses on request, if any: any element that is a view# of another parent element is resolved to its parent. In particular,# interacting with a view triggers reactive execution through the@@ -1065,6 +1067,8 @@ class Kernel:traceback.print_exc(file=tmpio)tmpio.seek(0)write_traceback(tmpio.read())+ else:+ updated_components.append(component)bound_names = (name@@ -1113,6 +1117,22 @@ class Kernel:# on_change handlersawait self._run_cells(set())+ for component in updated_components:+ try:+ component._on_update_completion()+ except Exception:+ # Internal marimo error+ sys.stderr.write(+ "An exception was raised when completing a UIElement's"+ "update. This is a bug in marimo. "+ "Please copy the below traceback and paste it in an "+ "issue: https://github.com/marimo-team/marimo/issues\n"+ )+ tmpio = io.StringIO()+ traceback.print_exc(file=tmpio)+ tmpio.seek(0)+ write_traceback(tmpio.read())+def get_ui_initial_value(self, object_id: str) -> Any:"""Get an initial value for a UIElement, if anydiff --git a/marimo/_smoke_tests/run_button.py b/marimo/_smoke_tests/run_button.pynew file mode 100644index 0000000000..92e5629b31--- /dev/null+++ b/marimo/_smoke_tests/run_button.py@@ -0,0 +1,47 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.6.11"+app = marimo.App()+++def __(mo):+ b = mo.ui.run_button()+ b+ return b,+++def __(mo):+ s = mo.ui.slider(1, 10)+ s+ return s,+++def __(b, mo, s):+ mo.stop(not b.value, "Click `run` to submit the slider's value")++ s.value+ return+++def __(b, mo):+ mo.stop(not b.value)++ import random+ random.randint(0, 1000)+ return random,+++def __():+ import marimo as mo+ return mo,+++if __name__ == "__main__":+ app.run()