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.

fix: enable rpcs unnamed UI elems (#1393)

Akshay Agrawal276a9622c23f
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 62d7a2120a..898085b6ff 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -80,6 +80,11 @@ class CellStaleState:
state: bool = False
+class CellOutput:
+ output: Any = None
+
+
@dataclasses.dataclass(frozen=True)
class CellImpl:
# hash of code
@@ -99,9 +104,12 @@ class CellImpl:
# Mutable fields
# config: explicit configuration of cell
config: CellConfig = dataclasses.field(default_factory=CellConfig)
- # status: status, inferred at runtime
+ # status: execution status, inferred at runtime
_status: CellStatus = dataclasses.field(default_factory=CellStatus)
+ # whether the cell is stale, inferred at runtime
_stale: CellStaleState = dataclasses.field(default_factory=CellStaleState)
+ # cells can optionally hold a reference to their output
+ _output: CellOutput = dataclasses.field(default_factory=CellOutput)
def configure(self, update: dict[str, Any] | CellConfig) -> CellImpl:
"""Update the cell config.
@@ -189,6 +197,13 @@ class CellImpl:
cell_id=self.cell_id, stale=stale, stream=stream
)
+ def set_output(self, output: Any) -> None:
+ self._output.output = output
+
+ @property
+ def output(self) -> Any:
+ return self._output.output
+
@dataclasses.dataclass
class Cell:
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 6478209ad1..3f1a76e143 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -9,9 +9,11 @@ from marimo._messaging.errors import (
from marimo._messaging.ops import CellOp, VariableValue, VariableValues
from marimo._messaging.tracebacks import write_traceback
from marimo._output import formatting
+from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.context.types import get_global_context
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.runner import cell_runner
+from marimo._utils.flatten import flatten
LOGGER = _loggers.marimo_logger()
@@ -45,6 +47,23 @@ def _broadcast_variables(
VariableValues(variables=values).broadcast()
+def _store_reference_to_output(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ del runner
+
+ # Stores a reference to the output if it contains a UIElement;
+ # this is required to make RPCs work for unnamed UI elements.
+ if isinstance(run_result.output, UIElement):
+ cell.set_output(run_result.output)
+ elif run_result.output is not None:
+ flattened, _ = flatten(run_result.output)
+ if any(isinstance(v, UIElement) for v in flattened):
+ cell.set_output(run_result.output)
+
+
def _broadcast_outputs(
cell: CellImpl,
runner: cell_runner.Runner,
@@ -140,6 +159,7 @@ def _reset_matplotlib_context(
POST_EXECUTION_HOOKS = [
_set_status_idle,
+ _store_reference_to_output,
_broadcast_variables,
_broadcast_outputs,
_reset_matplotlib_context,
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 5f4e79a61c..89fd54267d 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -557,10 +557,11 @@ class Kernel:
`exclude_defs`, and instructs the frontend to invalidate its UI
elements.
"""
+ cell = self.graph.cells[cell_id]
missing_modules_before_deletion = (
self.module_registry.missing_modules()
)
- defs_to_delete = self.graph.cells[cell_id].defs
+ defs_to_delete = cell.defs
self._delete_names(
defs_to_delete, exclude_defs if exclude_defs is not None else set()
)
@@ -589,6 +590,7 @@ class Kernel:
isolated=is_python_isolated(),
).broadcast()
+ cell.set_output(None)
get_context().cell_lifecycle_registry.dispose(
cell_id, deletion=deletion
)
diff --git a/pyproject.toml b/pyproject.toml
index f667e2898d..0a7cb5c897 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -300,3 +300,6 @@ extend-exclude = [
"**/__demo__/*",
"base64.test.ts",
]
+
+[tool.black]
+line-length = 79
diff --git a/tests/_cli/snapshots/ipynb.txt b/tests/_cli/snapshots/ipynb.txt
index b51916d9d1..0d8950a996 100644
--- a/tests/_cli/snapshots/ipynb.txt
+++ b/tests/_cli/snapshots/ipynb.txt
@@ -11,11 +11,14 @@
]
},
{
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"id": "MJUe",
"metadata": {},
+ "outputs": [],
"source": [
- "markdown"
+ "control_dep = None\n",
+ "mo.md(\"markdown\")"
]
},
{
@@ -25,6 +28,7 @@
"metadata": {},
"outputs": [],
"source": [
+ "control_dep\n",
"mo.md(f\"parametrized markdown {123}\")"
]
}
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index dd35e9e829..682d1dea01 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -15,6 +15,7 @@ from marimo._messaging.errors import (
)
from marimo._messaging.types import NoopStream
from marimo._plugins.ui._core.ids import IDProvider
+from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.dataflow import EdgeWithVar
from marimo._runtime.requests import (
AppMetadata,
@@ -738,6 +739,99 @@ class TestExecution:
assert "x" not in k.globals
+class TestStoredOutput:
+ async def test_ui_element_in_output_stored(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+
+ await k.run(
+ [
+ er := exec_req.get(
+ """
+ import marimo as mo
+
+ mo.ui.checkbox()
+ """
+ )
+ ]
+ )
+ cell = k.graph.cells[er.cell_id]
+ assert isinstance(cell.output, UIElement)
+
+ async def test_ui_element_in_nested_output_stored(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+
+ await k.run(
+ [
+ er := exec_req.get(
+ """
+ import marimo as mo
+
+ [mo.ui.checkbox()]
+ """
+ )
+ ]
+ )
+ cell = k.graph.cells[er.cell_id]
+ assert isinstance(cell.output[0], UIElement)
+
+ async def test_non_ui_elements_not_stored(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+
+ await k.run(
+ [
+ er := exec_req.get(
+ """
+ import marimo as mo
+
+ 'an output'
+ """
+ )
+ ]
+ )
+ cell = k.graph.cells[er.cell_id]
+ assert cell.output is None
+
+ async def test_cell_output_cleared_on_rerun(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+
+ await k.run(
+ [
+ er := exec_req.get(
+ """
+ import marimo as mo
+
+ mo.ui.checkbox()
+ """
+ )
+ ]
+ )
+ cell = k.graph.cells[er.cell_id]
+ assert isinstance(cell.output, UIElement)
+
+ await k.run(
+ [
+ exec_req.get_with_id(
+ er.cell_id,
+ """
+ import marimo as mo
+
+ raise ValueError
+ """,
+ )
+ ]
+ )
+ cell = k.graph.cells[er.cell_id]
+ assert cell.output is None
+
+
class TestDisable:
async def test_disable_and_reenable_not_stale(
self, any_kernel: Kernel, exec_req: ExecReqProvider
diff --git a/tests/conftest.py b/tests/conftest.py
index ab56dbcd34..61e6866013 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -278,11 +278,13 @@ def temp_marimo_file_with_md() -> Generator[str, None, None]:
@app.cell
def __(mo):
+ control_dep = None
mo.md("markdown")
- return
+ return control_dep
@app.cell
- def __(mo):
+ def __(mo, control_dep):
+ control_dep
mo.md(f"parametrized markdown {123}")
return