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: show which cell defines a variable in multiply-defined error (#9037)

Myles Scolnick280a1f64e071
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index cbe968cd0f..a5608f281f 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -927,10 +927,28 @@ class AsyncCodeModeContext:
"async with cm.get_context(skip_validation=True) as ctx"
)
if new_multiply_defined:
+ # Show which existing cell(s) already define each name.
+ # Only exclude cells that were actually (re)registered
+ # during this dry run. Moves and config-only updates
+ # do not register code, so their pre-existing
+ # definitions should still appear in the error details.
+ registered_ids = set(registered)
+ details: list[str] = []
+ for name in sorted(new_multiply_defined):
+ existing = graph.get_defining_cells(name) - registered_ids
+ if existing:
+ labels = ", ".join(
+ self._cell_label(cid) for cid in sorted(existing)
+ )
+ details.append(
+ f" - {name!r} is already defined in cell {labels}"
+ )
+ else:
+ details.append(f" - {name!r}")
raise RuntimeError(
- "Multiply-defined names: "
- f"{sorted(new_multiply_defined)}"
- f"{_skip_hint}"
+ "Multiply-defined names:\n"
+ + "\n".join(details)
+ + _skip_hint
)
if new_cycles:
raise RuntimeError(
diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.py
index f78a847f54..9e3c5b758d 100644
--- a/tests/_code_mode/test_context.py
+++ b/tests/_code_mode/test_context.py
@@ -372,6 +372,36 @@ class TestCombined:
assert k.globals["b"] == 101
assert "1" not in _graph_codes(k)
+ async def test_multiply_defined_error_shows_existing_cell(
+ self, k: Kernel
+ ) -> None:
+ """Error message for multiply-defined names includes the existing cell."""
+ await k.run([ExecuteCellCommand(cell_id=CellId_t("0"), code="x = 1")])
+
+ with _ctx(k) as ctx:
+ with pytest.raises(RuntimeError) as exc_info:
+ async with ctx as nb:
+ nb.create_cell("x = 2")
+ msg = str(exc_info.value)
+ assert "'x' is already defined in" in msg
+ assert "'0'" in msg
+
+ async def test_multiply_defined_two_new_cells_in_batch(
+ self, k: Kernel
+ ) -> None:
+ """Two new cells in the same batch defining the same name."""
+
+ async def _create_conflicting_cells() -> None:
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.create_cell("y = 1")
+ nb.create_cell("y = 2")
+
+ # No pre-existing cell owns 'y', so the name appears
+ # without an "already defined in" detail.
+ with pytest.raises(RuntimeError, match=r"'y'"):
+ await _create_conflicting_cells()
+
async def test_noop_batch(self, k: Kernel) -> None:
"""An empty context manager does nothing."""
await k.run([ExecuteCellCommand(cell_id=CellId_t("0"), code="x = 1")])