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.

feat: add __repr__, find(), and grep() to _CellsView and improve KeyError messages (#9034)

Myles Scolnick4f345a205479
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index 52b32d0296..b4bf67101b 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -164,7 +164,13 @@ class _CellsView:
if cell.name == target:
return cell.id
- raise KeyError(target)
+ available = ", ".join(c.id for c in self._doc.cells)
+ raise KeyError(
+ f"Cell {target!r} not found. "
+ f"Available cell IDs: [{available}]. "
+ f"IDs are stable across reorders — re-read ctx.cells "
+ f"if the notebook structure changed."
+ )
def __len__(self) -> int:
return len(self._doc)
@@ -205,6 +211,69 @@ class _CellsView:
"""Return (cell_id, cell_data) pairs in notebook order."""
return [(c.id, c) for c in self._doc.cells]
+ # ------------------------------------------------------------------
+ # Content search
+ # ------------------------------------------------------------------
+
+ def find(self, substring: str) -> list[NotebookCell]:
+ """Return cells whose code contains *substring*.
+
+ Performs a case-sensitive substring search on each cell's code.
+
+ Example::
+
+ ctx.cells.find("import marimo")
+ """
+ return [c for c in self._doc.cells if substring in c.code]
+
+ def grep(self, pattern: str) -> list[NotebookCell]:
+ """Return cells whose code matches the regex *pattern*.
+
+ Uses :func:`re.search` so the pattern can match anywhere in
+ the cell's code.
+
+ Example::
+
+ ctx.cells.grep(r"alt\\.Chart")
+ """
+ import re
+
+ compiled = re.compile(pattern)
+ return [c for c in self._doc.cells if compiled.search(c.code)]
+
+ # ------------------------------------------------------------------
+ # Display
+ # ------------------------------------------------------------------
+
+ def __repr__(self) -> str:
+ cells = self._doc.cells
+ n = len(cells)
+ max_shown = 10
+ lines = [f"CellsView({n} cell{'s' if n != 1 else ''}):"]
+
+ def _fmt(i: int, c: NotebookCell) -> str:
+ first_line = c.code.split("\n", 1)[0]
+ code_preview = first_line[:50]
+ if len(first_line) > 50:
+ code_preview += "..."
+ name_part = f" ({c.name})" if c.name else ""
+ return f" [{i}] {c.id}{name_part} | {code_preview}"
+
+ if n <= max_shown:
+ for i, c in enumerate(cells):
+ lines.append(_fmt(i, c))
+ else:
+ for i, c in enumerate(cells[:max_shown]):
+ lines.append(_fmt(i, c))
+ omitted = n - max_shown - 1
+ if omitted > 0:
+ lines.append(
+ f" ... {omitted} more cell"
+ f"{'s' if omitted != 1 else ''} ..."
+ )
+ lines.append(_fmt(n - 1, cells[-1]))
+ return "\n".join(lines)
+
# ------------------------------------------------------------------
# Context
diff --git a/tests/_code_mode/test_cells_view.py b/tests/_code_mode/test_cells_view.py
index 51bee8bde5..2e0ec0949d 100644
--- a/tests/_code_mode/test_cells_view.py
+++ b/tests/_code_mode/test_cells_view.py
@@ -9,7 +9,10 @@ import pytest
if TYPE_CHECKING:
from collections.abc import Generator
-from marimo._code_mode._context import AsyncCodeModeContext
+import re
+
+from marimo._ast.cell import CellConfig
+from marimo._code_mode._context import AsyncCodeModeContext, _CellsView
from marimo._messaging.notebook.document import (
NotebookCell,
NotebookDocument,
@@ -191,3 +194,172 @@ class TestCellsViewIteration:
assert "nonexistent" not in ctx.cells
assert 0 in ctx.cells
assert 5 not in ctx.cells
+
+
+# ------------------------------------------------------------------
+# Lightweight helper (no kernel needed)
+# ------------------------------------------------------------------
+
+
+def _cell(cell_id: str, code: str, name: str = "") -> NotebookCell:
+ return NotebookCell(
+ id=CellId_t(cell_id), code=code, name=name, config=CellConfig()
+ )
+
+
+def _view(cells: list[NotebookCell]) -> _CellsView:
+ doc = NotebookDocument(cells)
+ ctx = type("_MockCtx", (), {"_document": doc})()
+ return _CellsView(ctx) # type: ignore[arg-type]
+
+
+# ------------------------------------------------------------------
+# __repr__
+# ------------------------------------------------------------------
+
+
+class TestCellsViewRepr:
+ def test_repr_empty(self) -> None:
+ v = _view([])
+ assert repr(v) == "CellsView(0 cells):"
+
+ def test_repr_single_cell(self) -> None:
+ v = _view([_cell("a1", "x = 1")])
+ r = repr(v)
+ assert r.startswith("CellsView(1 cell):")
+ assert "[0] a1 | x = 1" in r
+
+ def test_repr_multiple_cells(self) -> None:
+ v = _view([_cell("a", "x = 1"), _cell("b", "y = 2")])
+ r = repr(v)
+ assert "CellsView(2 cells):" in r
+ assert "[0] a | x = 1" in r
+ assert "[1] b | y = 2" in r
+
+ def test_repr_with_name(self) -> None:
+ v = _view([_cell("a", "import marimo as mo", name="setup")])
+ assert "(setup)" in repr(v)
+
+ def test_repr_long_code_truncated(self) -> None:
+ long_code = "x = " + "a" * 60
+ v = _view([_cell("a", long_code)])
+ r = repr(v)
+ assert "..." in r
+ # First 50 chars of first line + "..."
+ assert long_code[:50] + "..." in r
+
+ def test_repr_multiline_shows_first_line(self) -> None:
+ v = _view([_cell("a", "line1\nline2\nline3")])
+ r = repr(v)
+ assert "line1" in r
+ assert "line2" not in r
+
+ def test_str_equals_repr(self) -> None:
+ v = _view([_cell("a", "x = 1")])
+ assert str(v) == repr(v)
+
+ def test_repr_many_cells_truncated(self) -> None:
+ cells = [_cell(f"c{i}", f"x{i} = {i}") for i in range(15)]
+ v = _view(cells)
+ r = repr(v)
+ assert "CellsView(15 cells):" in r
+ # First 10 shown
+ assert "[9]" in r
+ # Last cell shown
+ assert "[14]" in r
+ # Middle omitted
+ assert "... 4 more cells ..." in r
+ # Cell 11 not individually shown
+ assert "[11]" not in r
+
+
+# ------------------------------------------------------------------
+# find()
+# ------------------------------------------------------------------
+
+
+class TestCellsViewFind:
+ def test_find_match(self) -> None:
+ v = _view([_cell("a", "import marimo"), _cell("b", "x = 1")])
+ result = v.find("import")
+ assert len(result) == 1
+ assert result[0].id == "a"
+
+ def test_find_no_match(self) -> None:
+ v = _view([_cell("a", "x = 1")])
+ assert v.find("pandas") == []
+
+ def test_find_multiple_matches(self) -> None:
+ v = _view(
+ [
+ _cell("a", "import os"),
+ _cell("b", "x = 1"),
+ _cell("c", "import sys"),
+ ]
+ )
+ result = v.find("import")
+ assert [c.id for c in result] == ["a", "c"]
+
+ def test_find_case_sensitive(self) -> None:
+ v = _view([_cell("a", "import os")])
+ assert v.find("Import") == []
+
+
+# ------------------------------------------------------------------
+# grep()
+# ------------------------------------------------------------------
+
+
+class TestCellsViewGrep:
+ def test_grep_literal(self) -> None:
+ v = _view([_cell("a", "x = 1"), _cell("b", "y = 2")])
+ result = v.grep("x = 1")
+ assert len(result) == 1
+ assert result[0].id == "a"
+
+ def test_grep_regex(self) -> None:
+ v = _view(
+ [
+ _cell("a", "x = 1"),
+ _cell("b", "x=42"),
+ _cell("c", "y = 2"),
+ ]
+ )
+ result = v.grep(r"x\s*=\s*\d+")
+ assert [c.id for c in result] == ["a", "b"]
+
+ def test_grep_no_match(self) -> None:
+ v = _view([_cell("a", "x = 1")])
+ assert v.grep(r"zzz\d+") == []
+
+ def test_grep_multiline_cell(self) -> None:
+ v = _view([_cell("a", "line1\nline2_match\nline3")])
+ result = v.grep("line2_match")
+ assert len(result) == 1
+
+ def test_grep_invalid_regex_raises(self) -> None:
+ v = _view([_cell("a", "x = 1")])
+ with pytest.raises(re.error):
+ v.grep("[invalid")
+
+
+# ------------------------------------------------------------------
+# Error messages
+# ------------------------------------------------------------------
+
+
+class TestCellsViewErrorMessages:
+ def test_error_lists_available_ids(self) -> None:
+ v = _view([_cell("abcd", "x = 1"), _cell("efgh", "y = 2")])
+ with pytest.raises(KeyError, match="not found"):
+ v["MzAK"]
+
+ def test_error_mentions_stability(self) -> None:
+ v = _view([_cell("abcd", "x = 1")])
+ with pytest.raises(KeyError, match="stable across reorders"):
+ v["gone"]
+
+ def test_error_shows_available(self) -> None:
+ v = _view([_cell("abcd", "x = 1")])
+ with pytest.raises(KeyError, match="abcd"):
+ v["missing"]