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.

Separate cell editing from cell execution (#8757)

Trevor Manz142d74619ba2
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index 42a6ece72f..6264bc3617 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -12,10 +12,13 @@ Usage::
async with cm.get_context() as ctx:
cid = ctx.create_cell("x = 1")
- ctx.create_cell("y = x + 1", after=cid)
+ cid2 = ctx.create_cell("y = x + 1", after=cid)
ctx.edit_cell("my_cell", code="z = 42")
ctx.delete_cell("old_cell")
ctx.move_cell("my_cell", after="other_cell")
+ ctx.run_cell(cid)
+ ctx.run_cell(cid2)
+ ctx.run_cell("my_cell")
"""
from __future__ import annotations
@@ -241,6 +244,7 @@ class AsyncCodeModeContext:
self._id_generator.seen_ids = set(kernel.graph.cells.keys())
self._packages_to_install: list[str] = []
self._ui_updates: list[tuple[UIElementId, Any]] = []
+ self._cells_to_run: set[CellId_t] = set()
self._entered = False
def _require_entered(self) -> None:
@@ -263,6 +267,7 @@ class AsyncCodeModeContext:
self._pending_adds = {}
self._packages_to_install = []
self._ui_updates = []
+ self._cells_to_run = set()
self._entered = True
return self
@@ -275,10 +280,12 @@ class AsyncCodeModeContext:
ops = self._ops
packages = self._packages_to_install
ui_updates = self._ui_updates
+ cells_to_run = self._cells_to_run
self._ops = []
self._pending_adds = {}
self._packages_to_install = []
self._ui_updates = []
+ self._cells_to_run = set()
if exc_type is not None:
return # let exception propagate, discard queued ops
@@ -296,7 +303,10 @@ class AsyncCodeModeContext:
_validate_ops(ops)
if self._check:
self._dry_run_compile(ops)
- await self._apply_ops(ops)
+ await self._apply_ops(ops, cells_to_run)
+ elif cells_to_run:
+ # run_cell was called without any structural ops — just re-run.
+ await self._kernel._run_cells(cells_to_run)
# Flush queued UI updates as a single batch.
if ui_updates:
@@ -309,7 +319,7 @@ class AsyncCodeModeContext:
)
# Print a summary of what was applied.
- self._print_summary(ops, packages, ui_updates)
+ self._print_summary(ops, packages, ui_updates, cells_to_run)
# ------------------------------------------------------------------
# Summary
@@ -320,6 +330,7 @@ class AsyncCodeModeContext:
ops: list[_Op],
packages: list[str],
ui_updates: list[tuple[UIElementId, Any]],
+ cells_to_run: set[CellId_t] | None = None,
) -> None:
"""Print a human-readable summary of applied operations."""
lines: list[str] = []
@@ -327,11 +338,16 @@ class AsyncCodeModeContext:
for pkg in packages:
lines.append(f"installed {pkg}")
+ _run = cells_to_run or set()
+ op_cell_ids: set[CellId_t] = set()
for op in ops:
cell_id = op.cell_id
+ op_cell_ids.add(cell_id)
label = self._cell_label(cell_id)
+ ran = cell_id in _run
if isinstance(op, _AddOp):
- lines.append(f"created cell {label}")
+ verb = "created and ran" if ran else "created"
+ lines.append(f"{verb} cell {label}")
elif isinstance(op, _UpdateOp):
parts = []
if op.code is not None:
@@ -339,12 +355,20 @@ class AsyncCodeModeContext:
if op.config is not None:
parts.append("config")
detail = " and ".join(parts) if parts else "config"
- lines.append(f"edited {detail} of cell {label}")
+ suffix = " and ran" if ran else ""
+ lines.append(f"edited {detail} of cell {label}{suffix}")
elif isinstance(op, _DeleteOp):
lines.append(f"deleted cell {label}")
elif isinstance(op, _MoveOp):
lines.append(f"moved cell {label}")
+ # Report cells queued for execution that had no structural op.
+ if _run:
+ for cell_id in _run:
+ if cell_id not in op_cell_ids:
+ label = self._cell_label(cell_id)
+ lines.append(f"re-ran cell {label}")
+
if ui_updates:
lines.append(f"updated {len(ui_updates)} UI element(s)")
@@ -355,14 +379,19 @@ class AsyncCodeModeContext:
sys.stdout.write(line + "\n")
def _cell_label(self, cell_id: CellId_t) -> str:
- """Return a display label for a cell: name if available, else short ID."""
+ """Return a display label: ``'id' (name)`` or ``'id'``."""
+ short = repr(str(cell_id)[:8])
+ name: str | None = None
cm = self._cell_manager
if cm is not None:
data = cm.get_cell_data(cell_id)
if data and data.name:
- return repr(data.name)
- short = str(cell_id)[:8]
- return repr(short)
+ name = data.name
+ if name is None:
+ name = _cell_names.get(cell_id)
+ if name:
+ return f"{short} ({name})"
+ return short
# ------------------------------------------------------------------
# Read-only attributes
@@ -461,7 +490,6 @@ class AsyncCodeModeContext:
hide_code: bool = True,
disabled: bool = False,
column: int | None = None,
- draft: bool = False,
name: str | None = None,
) -> CellId_t:
"""Queue a new cell. Returns the new cell's ID.
@@ -469,6 +497,12 @@ class AsyncCodeModeContext:
The returned ID can be used in subsequent operations within the
same batch (e.g. as an ``after`` target for the next cell).
+ Cells are not executed automatically. Use ``run_cell`` to queue
+ them for execution::
+
+ cid = ctx.create_cell("x = 1")
+ ctx.run_cell(cid)
+
Examples:
```python
# Append at the end
@@ -478,11 +512,9 @@ class AsyncCodeModeContext:
cid2 = ctx.create_cell("df = pd.read_csv('data.csv')", after=cid)
ctx.create_cell("df.head()", after=cid2)
- # Insert before a named cell, with code visible
- ctx.create_cell("# Setup", before="analysis", hide_code=False)
-
- # Stage without executing
- ctx.create_cell("expensive_computation()", draft=True)
+ # Create and run
+ cid = ctx.create_cell("x = 1")
+ ctx.run_cell(cid)
# Create a setup cell with imports, then a cell that uses them
ctx.create_cell("import marimo as mo", name="setup")
@@ -500,8 +532,6 @@ class AsyncCodeModeContext:
disabled (bool): Prevent the cell from executing.
Defaults to False.
column (int, optional): Column index for multi-column layouts.
- draft (bool): Insert code without executing it.
- Defaults to False.
name (str, optional): Name for the cell (e.g. ``"data_loader"``,
``"setup"`` for a setup cell).
"""
@@ -524,7 +554,6 @@ class AsyncCodeModeContext:
cell_id=cell_id,
code=code,
config=config,
- draft=draft,
before=before_id,
after=after_id,
name=resolved_name,
@@ -541,7 +570,6 @@ class AsyncCodeModeContext:
hide_code: bool | None = None,
disabled: bool | None = None,
column: int | None = None,
- draft: bool = False,
name: str | None = None,
) -> None:
"""Queue an update to an existing cell's code and/or config.
@@ -549,6 +577,12 @@ class AsyncCodeModeContext:
Only the arguments you explicitly pass are changed — the cell's
existing config is preserved for any argument left as ``None``.
+ Editing a cell does not automatically execute it. Use ``run_cell``
+ to queue it for execution::
+
+ ctx.edit_cell("my_cell", code="x = 42")
+ ctx.run_cell("my_cell")
+
Examples:
```python
# Update only code (config like hide_code is preserved)
@@ -562,8 +596,9 @@ class AsyncCodeModeContext:
# Update both code and config
ctx.edit_cell("data_loader", code="df = load()", disabled=True)
- # Stage new code without executing
- ctx.edit_cell("my_cell", code="new_code()", draft=True)
+ # Edit and run
+ ctx.edit_cell("my_cell", code="new_code()")
+ ctx.run_cell("my_cell")
# Rename a cell
ctx.edit_cell("old_name", name="new_name")
@@ -575,7 +610,6 @@ class AsyncCodeModeContext:
hide_code (bool, optional): Collapse the code editor. None keeps existing.
disabled (bool, optional): Prevent the cell from executing. None keeps existing.
column (int, optional): Column index for multi-column layouts. None keeps existing.
- draft (bool): Update code without executing. Defaults to False.
name (str, optional): New name for the cell. None keeps existing.
"""
self._require_entered()
@@ -630,7 +664,6 @@ class AsyncCodeModeContext:
cell_id=cell_id,
code=code,
config=config,
- draft=draft,
name=name,
new_cell_id=new_cell_id,
)
@@ -697,6 +730,47 @@ class AsyncCodeModeContext:
)
)
+ def run_cell(self, target: str) -> None:
+ """Queue a cell for execution.
+
+ Cells created or edited in the same batch are not executed
+ automatically — use ``run_cell`` to mark them for execution.
+ Can also be used to re-run an existing cell without editing it.
+
+ All queued ``run_cell`` targets are executed in a single batch
+ on context exit, after structural operations (create/edit/delete)
+ have been applied.
+
+ Examples:
+ ```python
+ # Create and run
+ cid = ctx.create_cell("x = 1")
+ ctx.run_cell(cid)
+
+ # Edit and run
+ ctx.edit_cell("my_cell", code="y = 2")
+ ctx.run_cell("my_cell")
+
+ # Re-run an existing cell without editing
+ ctx.run_cell("my_cell")
+ ```
+
+ Args:
+ target (str): Cell ID or cell name to execute.
+ """
+ self._require_entered()
+ cell_id = self._resolve_target(target)
+ # Guard against running a cell that is queued for deletion.
+ deleted_ids = {
+ op.cell_id for op in self._ops if isinstance(op, _DeleteOp)
+ }
+ if cell_id in deleted_ids:
+ raise ValueError(
+ f"Cannot run cell {target!r} because it is queued "
+ "for deletion in this batch"
+ )
+ self._cells_to_run.add(cell_id)
+
# ------------------------------------------------------------------
# Apply queued operations
# ------------------------------------------------------------------
@@ -787,7 +861,9 @@ class AsyncCodeModeContext:
if evicted:
graph.topology.reorder_nodes(original_order)
- async def _apply_ops(self, ops: list[_Op]) -> None:
+ async def _apply_ops(
+ self, ops: list[_Op], explicit_run: set[CellId_t] | None = None
+ ) -> None:
"""Validate, plan, format, and apply a batch of operations."""
existing_ids = list(self.graph.cells.keys())
plan = _build_plan(existing_ids, ops)
@@ -805,7 +881,6 @@ class AsyncCodeModeContext:
# Classify each entry.
code_entries: list[_PlanEntry] = [] # new or changed code
config_entries: list[_PlanEntry] = [] # config-only changes
- draft_ids: set[CellId_t] = set()
for entry in plan:
is_new = entry.cell_id not in existing_id_set
@@ -815,8 +890,6 @@ class AsyncCodeModeContext:
)
if is_new or code_changed:
code_entries.append(entry)
- if entry.draft:
- draft_ids.add(entry.cell_id)
elif entry.config is not None:
config_entries.append(entry)
@@ -875,10 +948,18 @@ class AsyncCodeModeContext:
del _cell_names[op.cell_id]
# Notify frontend of all changes (code and config-only).
+ # Cells not queued for execution are marked as stale.
+ # Config-only changes are never stale (the code didn't change).
+ _run_set = explicit_run or set()
+ _code_entry_ids = {e.cell_id for e in code_entries}
all_entries = code_entries + config_entries
by_stale: dict[bool, list[_PlanEntry]] = {}
for entry in all_entries:
- by_stale.setdefault(entry.draft, []).append(entry)
+ is_stale = (
+ entry.cell_id in _code_entry_ids
+ and entry.cell_id not in _run_set
+ )
+ by_stale.setdefault(is_stale, []).append(entry)
for is_stale, entries in by_stale.items():
names = [_cell_names.get(e.cell_id, "") for e in entries]
@@ -925,10 +1006,12 @@ class AsyncCodeModeContext:
self.notify(UpdateCellIdsNotification(cell_ids=target_order))
- # Run cells, excluding drafts.
- cells_to_run -= draft_ids
- if cells_to_run:
- await self._kernel._run_cells(cells_to_run)
+ # Only run cells explicitly queued via run_cell(), filtered to
+ # cells that still exist after structural ops have been applied.
+ if _run_set:
+ cells_to_run = _run_set & set(self.graph.cells.keys())
+ if cells_to_run:
+ await self._kernel._run_cells(cells_to_run)
# ------------------------------------------------------------------
# Formatting helpers
diff --git a/marimo/_code_mode/_plan.py b/marimo/_code_mode/_plan.py
index 1836d471dd..9c3b4dc57f 100644
--- a/marimo/_code_mode/_plan.py
+++ b/marimo/_code_mode/_plan.py
@@ -18,7 +18,6 @@ class _AddOp:
cell_id: CellId_t
code: str
config: CellConfig
- draft: bool = False
before: CellId_t | None = None
after: CellId_t | None = None
name: str | None = None
@@ -29,7 +28,6 @@ class _UpdateOp:
cell_id: CellId_t
code: str | None = None
config: CellConfig | None = None
- draft: bool = False
name: str | None = None
new_cell_id: CellId_t | None = None
@@ -59,7 +57,6 @@ class _PlanEntry:
cell_id: CellId_t
code: str | None = None
config: CellConfig | None = None
- draft: bool = False
name: str | None = None
@@ -93,7 +90,6 @@ def _build_plan(
cell_id=op.cell_id,
code=op.code,
config=op.config,
- draft=op.draft,
name=op.name,
)
if op.after is not None:
@@ -117,7 +113,6 @@ def _build_plan(
entry.config = op.config
if op.name is not None:
entry.name = op.name
- entry.draft = op.draft
elif isinstance(op, _DeleteOp):
idx = _find_index(op.cell_id)
diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.py
index 705dc54e64..e6ff97a588 100644
--- a/tests/_code_mode/test_context.py
+++ b/tests/_code_mode/test_context.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from unittest.mock import AsyncMock, patch
import msgspec
+import pytest
from inline_snapshot import snapshot
from marimo._code_mode._context import AsyncCodeModeContext
@@ -45,7 +46,8 @@ class TestAddCell:
_clear_messages(k)
async with ctx as nb:
- nb.create_cell("x = 1")
+ cid = nb.create_cell("x = 1")
+ nb.run_cell(cid)
assert len(k.graph.cells) == 1
cell = list(k.graph.cells.values())[0]
@@ -72,7 +74,8 @@ class TestAddCell:
_clear_messages(k)
async with ctx as nb:
- nb.create_cell("c = a + b")
+ cid = nb.create_cell("c = a + b")
+ nb.run_cell(cid)
assert len(k.graph.cells) == 3
assert k.globals["c"] == 30
@@ -103,12 +106,12 @@ class TestAddCell:
# New cell should be after "0", before "1".
assert cell_ids[2] == "1"
- async def test_add_draft_does_not_execute(self, k: Kernel) -> None:
+ async def test_add_without_run_does_not_execute(self, k: Kernel) -> None:
ctx = AsyncCodeModeContext(k)
_clear_messages(k)
async with ctx as nb:
- nb.create_cell("x = 999", draft=True)
+ nb.create_cell("x = 999")
assert len(k.graph.cells) == 1
assert "x" not in k.globals
@@ -132,7 +135,9 @@ class TestAddCell:
async with ctx as nb:
cid1 = nb.create_cell("x = 1")
- nb.create_cell("y = 2", after=cid1)
+ cid2 = nb.create_cell("y = 2", after=cid1)
+ nb.run_cell(cid1)
+ nb.run_cell(cid2)
assert k.globals["x"] == 1
assert k.globals["y"] == 2
@@ -207,6 +212,7 @@ class TestUpdateCell:
async with ctx as nb:
nb.edit_cell("0", code="x = 42")
+ nb.run_cell("0")
assert k.globals["x"] == 42
assert _graph_codes(k) == snapshot({"0": "x = 42"})
@@ -239,6 +245,7 @@ class TestUpdateCell:
ctx = AsyncCodeModeContext(k)
async with ctx as nb:
nb.edit_cell("0", code="x = 42")
+ nb.run_cell("0")
assert k.globals["x"] == 42
assert "y" not in k.globals
@@ -258,6 +265,7 @@ class TestUpdateCell:
ctx = AsyncCodeModeContext(k)
async with ctx as nb:
nb.edit_cell("0", code="x = 42")
+ nb.run_cell("0")
assert k.globals["x"] == 42
assert k.cell_metadata["0"].config.hide_code is True
@@ -308,7 +316,8 @@ class TestCombined:
async with ctx as nb:
nb.delete_cell("1")
- nb.create_cell("d = a + c", after="0")
+ cid = nb.create_cell("d = a + c", after="0")
+ nb.run_cell(cid)
assert k.globals["d"] == 4
codes = _graph_codes(k)
@@ -331,7 +340,8 @@ class TestCombined:
# This must not raise a multiply-defined error.
async with ctx as nb:
nb.delete_cell("1")
- nb.create_cell("b = a + 100")
+ cid = nb.create_cell("b = a + 100")
+ nb.run_cell(cid)
assert k.globals["b"] == 101
assert "1" not in _graph_codes(k)
@@ -363,6 +373,46 @@ class TestCombined:
assert _graph_codes(k) == snapshot({"0": "x = 1"})
assert len(k.graph.cells) == 1
+ async def test_rerun_without_structural_ops(self, k: Kernel) -> None:
+ """run_cell without any create/edit/delete still executes."""
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ # Mutate the global so we can detect re-execution.
+ k.globals["x"] = 0
+ async with ctx as nb:
+ nb.run_cell("0")
+
+ assert k.globals["x"] == 1
+
+ async def test_rerun_alongside_structural_ops(self, k: Kernel) -> None:
+ """run_cell on an unchanged cell works even with other structural ops."""
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="x = 1"),
+ ExecuteCellCommand(cell_id="1", code="y = x + 1"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+
+ # Mutate so we can detect re-execution of "0".
+ k.globals["x"] = 0
+ async with ctx as nb:
+ nb.create_cell("z = 99", name="new")
+ nb.run_cell("0")
+
+ assert k.globals["x"] == 1
+
+ async def test_run_deleted_cell_raises(self, k: Kernel) -> None:
+ """Calling run_cell on a cell queued for deletion raises."""
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb:
+ nb.delete_cell("0")
+ with pytest.raises(ValueError, match="queued for deletion"):
+ nb.run_cell("0")
+
class TestSummary:
async def test_create_prints_summary(
@@ -371,10 +421,10 @@ class TestSummary:
ctx = AsyncCodeModeContext(k)
async with ctx as nb:
- nb.create_cell("x = 1")
+ nb.create_cell("x = 1", name="my_cell")
captured = capsys.readouterr() # type: ignore[attr-defined]
- assert "created cell" in captured.out
+ assert captured.out == snapshot("created cell 'Hbol' (my_cell)\n")
async def test_edit_prints_summary(
self, k: Kernel, capsys: object
@@ -386,7 +436,7 @@ class TestSummary:
nb.edit_cell("0", code="x = 2")
captured = capsys.readouterr() # type: ignore[attr-defined]
- assert "edited code of cell" in captured.out
+ assert captured.out == snapshot("edited code of cell '0'\n")
async def test_delete_prints_summary(
self, k: Kernel, capsys: object
@@ -398,7 +448,7 @@ class TestSummary:
nb.delete_cell("0")
captured = capsys.readouterr() # type: ignore[attr-defined]
- assert "deleted cell" in captured.out
+ assert captured.out == snapshot("deleted cell '0'\n")
async def test_noop_prints_nothing(
self, k: Kernel, capsys: object
@@ -411,26 +461,39 @@ class TestSummary:
captured = capsys.readouterr() # type: ignore[attr-defined]
assert captured.out == ""
- async def test_mixed_ops_prints_all(
- self, k: Kernel, capsys: object
- ) -> None:
+ async def test_batch_summary(self, k: Kernel, capsys: object) -> None:
+ """Full batch: create+run, edit+run, delete, create (staged), re-run."""
await k.run(
[
ExecuteCellCommand(cell_id="0", code="a = 1"),
ExecuteCellCommand(cell_id="1", code="b = 2"),
+ ExecuteCellCommand(cell_id="2", code="c = 3"),
]
)
ctx = AsyncCodeModeContext(k)
async with ctx as nb:
+ # delete
nb.delete_cell("1")
- nb.create_cell("c = 3")
+ # create + run
+ nb.create_cell("d = 4", name="new_cell")
+ nb.run_cell("new_cell")
+ # create without run (staged)
+ nb.create_cell("e = 5", name="staged")
+ # edit + run
nb.edit_cell("0", code="a = 10")
+ nb.run_cell("0")
+ # re-run existing cell without editing
+ nb.run_cell("2")
captured = capsys.readouterr() # type: ignore[attr-defined]
- assert "deleted cell" in captured.out
- assert "created cell" in captured.out
- assert "edited code of cell" in captured.out
+ assert captured.out == snapshot("""\
+deleted cell '1'
+created and ran cell 'Hbol' (new_cell)
+created cell 'MJUe' (staged)
+edited code of cell '0' and ran
+re-ran cell '2'
+""")
class TestResolveTarget:
@@ -439,8 +502,10 @@ class TestResolveTarget:
ctx = AsyncCodeModeContext(k)
async with ctx as nb:
- nb.create_cell("x = 1", name="first")
- nb.create_cell("y = x + 1", after="first")
+ cid1 = nb.create_cell("x = 1", name="first")
+ cid2 = nb.create_cell("y = x + 1", after="first")
+ nb.run_cell(cid1)
+ nb.run_cell(cid2)
assert k.globals["x"] == 1
assert k.globals["y"] == 2
@@ -463,7 +528,8 @@ class TestResolveTarget:
async with ctx as nb:
nb.edit_cell("0", name="renamed")
- nb.create_cell("c = a + b", after="renamed")
+ cid = nb.create_cell("c = a + b", after="renamed")
+ nb.run_cell(cid)
assert k.globals["c"] == 3