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.

Make _CellsView behave like a read-only ordered dict (#8778)

Trevor Manz3e2c6fabbeed
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index 6264bc3617..331f0dbc8c 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -82,7 +82,7 @@ class NotebookCellData:
code: str | None = None
config: CellConfig | None = None
- cell_id: CellId_t = field(default_factory=lambda: CellId_t(str(uuid4())))
+ id: CellId_t = field(default_factory=lambda: CellId_t(str(uuid4())))
name: str | None = field(default=None, repr=True, compare=False)
@@ -124,7 +124,7 @@ def get_context(*, check: bool = True) -> AsyncCodeModeContext:
class _CellsView:
- """Read-only view over notebook cells as ``NotebookCellData`` objects.
+ """Read-only, ordered-dict-like view over notebook cells.
Supports lookup by integer index, cell ID, or cell name::
@@ -132,6 +132,14 @@ class _CellsView:
ctx.cells[-1] # negative index
ctx.cells["Abcd1234"] # by cell ID
ctx.cells["my_cell"] # by cell name
+
+ Dict-like iteration::
+
+ for cid, cell in ctx.cells.items():
+ ...
+ ctx.cells.keys() # list of CellId_t
+ ctx.cells.values() # list of NotebookCellData
+ "my_cell" in ctx.cells # membership test
"""
def __init__(self, ctx: AsyncCodeModeContext) -> None:
@@ -159,7 +167,7 @@ class _CellsView:
code=cell_impl.code,
config=meta.config if meta else CellConfig(),
name=self._cell_name(cell_id),
- cell_id=cell_id,
+ id=cell_id,
)
def _resolve(self, target: str) -> CellId_t:
@@ -199,9 +207,31 @@ class _CellsView:
return self._build_at(self._resolve(key))
- def __iter__(self) -> Iterator[NotebookCellData]:
- for cid in self._cell_ids():
- yield self._build_at(cid)
+ def __iter__(self) -> Iterator[CellId_t]:
+ yield from self._cell_ids()
+
+ def __contains__(self, key: object) -> bool:
+ if isinstance(key, int):
+ return 0 <= key < len(self)
+ if isinstance(key, str):
+ try:
+ self._resolve(key)
+ return True
+ except KeyError:
+ return False
+ return False
+
+ def keys(self) -> list[CellId_t]:
+ """Return cell IDs in notebook order."""
+ return self._cell_ids()
+
+ def values(self) -> list[NotebookCellData]:
+ """Return cell data in notebook order."""
+ return [self._build_at(cid) for cid in self._cell_ids()]
+
+ def items(self) -> list[tuple[CellId_t, NotebookCellData]]:
+ """Return (cell_id, cell_data) pairs in notebook order."""
+ return [(cid, self._build_at(cid)) for cid in self._cell_ids()]
# ------------------------------------------------------------------
diff --git a/tests/_code_mode/test_cells_view.py b/tests/_code_mode/test_cells_view.py
index 790908f4ba..a1c130ba48 100644
--- a/tests/_code_mode/test_cells_view.py
+++ b/tests/_code_mode/test_cells_view.py
@@ -6,6 +6,11 @@ import pytest
from marimo._code_mode._context import AsyncCodeModeContext, NotebookCellData
from marimo._runtime.commands import ExecuteCellCommand
from marimo._runtime.runtime import Kernel
+from marimo._types.ids import CellId_t
+
+
+def cmd(cell_id: str, code: str) -> ExecuteCellCommand:
+ return ExecuteCellCommand(cell_id=CellId_t(cell_id), code=code)
class TestCellsViewIndex:
@@ -14,33 +19,33 @@ class TestCellsViewIndex:
async def test_positive_index(self, k: Kernel) -> None:
await k.run(
[
- ExecuteCellCommand(cell_id="a", code="x = 1"),
- ExecuteCellCommand(cell_id="b", code="y = 2"),
- ExecuteCellCommand(cell_id="c", code="z = 3"),
+ cmd(cell_id="a", code="x = 1"),
+ cmd(cell_id="b", code="y = 2"),
+ cmd(cell_id="c", code="z = 3"),
]
)
ctx = AsyncCodeModeContext(k)
- assert ctx.cells[0].cell_id == "a"
- assert ctx.cells[1].cell_id == "b"
- assert ctx.cells[2].cell_id == "c"
+ assert ctx.cells[0].id == "a"
+ assert ctx.cells[1].id == "b"
+ assert ctx.cells[2].id == "c"
async def test_negative_index(self, k: Kernel) -> None:
await k.run(
[
- ExecuteCellCommand(cell_id="a", code="x = 1"),
- ExecuteCellCommand(cell_id="b", code="y = 2"),
- ExecuteCellCommand(cell_id="c", code="z = 3"),
+ cmd(cell_id="a", code="x = 1"),
+ cmd(cell_id="b", code="y = 2"),
+ cmd(cell_id="c", code="z = 3"),
]
)
ctx = AsyncCodeModeContext(k)
- assert ctx.cells[-1].cell_id == "c"
- assert ctx.cells[-2].cell_id == "b"
- assert ctx.cells[-3].cell_id == "a"
+ assert ctx.cells[-1].id == "c"
+ assert ctx.cells[-2].id == "b"
+ assert ctx.cells[-3].id == "a"
async def test_index_out_of_range(self, k: Kernel) -> None:
- await k.run([ExecuteCellCommand(cell_id="a", code="x = 1")])
+ await k.run([cmd(cell_id="a", code="x = 1")])
ctx = AsyncCodeModeContext(k)
with pytest.raises(IndexError):
@@ -56,18 +61,18 @@ class TestCellsViewCellId:
async def test_lookup_by_cell_id(self, k: Kernel) -> None:
await k.run(
[
- ExecuteCellCommand(cell_id="abc", code="x = 1"),
- ExecuteCellCommand(cell_id="def", code="y = 2"),
+ cmd(cell_id="abc", code="x = 1"),
+ cmd(cell_id="def", code="y = 2"),
]
)
ctx = AsyncCodeModeContext(k)
cell = ctx.cells["def"]
- assert cell.cell_id == "def"
+ assert cell.id == "def"
assert cell.code == "y = 2"
async def test_lookup_by_cell_id_not_found(self, k: Kernel) -> None:
- await k.run([ExecuteCellCommand(cell_id="abc", code="x = 1")])
+ await k.run([cmd(cell_id="abc", code="x = 1")])
ctx = AsyncCodeModeContext(k)
with pytest.raises(KeyError):
@@ -78,7 +83,7 @@ class TestCellsViewCellName:
"""Test lookup by cell name."""
async def test_name_lookup_without_cell_manager(self, k: Kernel) -> None:
- await k.run([ExecuteCellCommand(cell_id="a", code="x = 1")])
+ await k.run([cmd(cell_id="a", code="x = 1")])
ctx = AsyncCodeModeContext(k)
# No cell manager → name lookup fails
@@ -90,7 +95,7 @@ class TestCellsViewNameField:
"""Test that the name field is populated on NotebookCellData."""
async def test_name_is_none_without_cell_manager(self, k: Kernel) -> None:
- await k.run([ExecuteCellCommand(cell_id="a", code="x = 1")])
+ await k.run([cmd(cell_id="a", code="x = 1")])
ctx = AsyncCodeModeContext(k)
cell = ctx.cells[0]
@@ -107,21 +112,70 @@ class TestCellsViewIteration:
async def test_len(self, k: Kernel) -> None:
await k.run(
[
- ExecuteCellCommand(cell_id="a", code="x = 1"),
- ExecuteCellCommand(cell_id="b", code="y = 2"),
+ cmd(cell_id="a", code="x = 1"),
+ cmd(cell_id="b", code="y = 2"),
]
)
ctx = AsyncCodeModeContext(k)
assert len(ctx.cells) == 2
- async def test_iteration(self, k: Kernel) -> None:
+ async def test_iteration_yields_cell_ids(self, k: Kernel) -> None:
await k.run(
[
- ExecuteCellCommand(cell_id="a", code="x = 1"),
- ExecuteCellCommand(cell_id="b", code="y = 2"),
+ cmd(cell_id="a", code="x = 1"),
+ cmd(cell_id="b", code="y = 2"),
]
)
ctx = AsyncCodeModeContext(k)
- ids = [cell.cell_id for cell in ctx.cells]
+ ids = list(ctx.cells)
assert ids == ["a", "b"]
+
+ async def test_keys(self, k: Kernel) -> None:
+ await k.run(
+ [
+ cmd(cell_id="a", code="x = 1"),
+ cmd(cell_id="b", code="y = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ assert ctx.cells.keys() == ["a", "b"]
+
+ async def test_values(self, k: Kernel) -> None:
+ await k.run(
+ [
+ cmd(cell_id="a", code="x = 1"),
+ cmd(cell_id="b", code="y = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ vals = ctx.cells.values()
+ assert [v.id for v in vals] == ["a", "b"]
+ assert [v.code for v in vals] == ["x = 1", "y = 2"]
+
+ async def test_items(self, k: Kernel) -> None:
+ await k.run(
+ [
+ cmd(cell_id="a", code="x = 1"),
+ cmd(cell_id="b", code="y = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ items = ctx.cells.items()
+ assert [(cid, cell.code) for cid, cell in items] == [
+ ("a", "x = 1"),
+ ("b", "y = 2"),
+ ]
+
+ async def test_contains(self, k: Kernel) -> None:
+ await k.run(
+ [
+ cmd(cell_id="a", code="x = 1"),
+ cmd(cell_id="b", code="y = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ assert "a" in ctx.cells
+ assert "nonexistent" not in ctx.cells
+ assert 0 in ctx.cells
+ assert 5 not in ctx.cells