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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: reject invalid code mode cell names (#11032)
Shahmir Varqha70fe77a46cc8
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.pyindex e1f35bebd8..ecc4c87968 100644--- a/marimo/_code_mode/_context.py+++ b/marimo/_code_mode/_context.py@@ -23,7 +23,9 @@ Usage::from __future__ import annotations+import keywordimport sys+import unicodedatafrom dataclasses import dataclassfrom enum import Enumfrom typing import TYPE_CHECKING, Any, Literal, Protocol, cast, overload@@ -39,7 +41,7 @@ from marimo._ast.cell import ()from marimo._ast.cell_id import CellIdGeneratorfrom marimo._ast.compiler import compile_cell-from marimo._ast.names import SETUP_CELL_NAME+from marimo._ast.names import SETUP_CELL_NAME, is_internal_cell_namefrom marimo._code_mode._better_inspect import _HelpableEnumMeta, helpablefrom marimo._code_mode._packages import (PackageResult,@@ -110,6 +112,26 @@ if TYPE_CHECKING:from marimo._runtime.runtime import Kernel+def _validate_cell_name(name: str | None) -> None:+ if name is None or name == "":+ return+ if is_internal_cell_name(name):+ raise ValueError(+ f"Invalid cell name {name!r}. {name!r} is reserved for unnamed "+ "cells."+ )+ if unicodedata.normalize("NFKC", name) != name:+ raise ValueError(+ f"Invalid cell name {name!r}. Cell names must be NFKC-normalized."+ )+ if not name.isidentifier() or keyword.iskeyword(name):+ raise ValueError(+ f"Invalid cell name {name!r}. Cell names must be valid, "+ "non-keyword Python identifiers, such as 'load_data' or "+ "'analysis_summary'."+ )++@helpableclass CellStatusType(str, Enum, metaclass=_HelpableEnumMeta):"""Synthesized cell execution status.@@ -1100,15 +1122,16 @@ class AsyncCodeModeContext:expand_output (bool): Show the cell's output in full instead ofclamping it to a fixed height. Defaults to False.column (int, optional): Column index for multi-column layouts.- name (str, optional): Cell names are a human-facing label,- reserved for special cases (e.g. `"setup"`). Prefer- referencing cells by the returned cell ID unless- naming is important for the user.+ name (str, optional): New name for the cell. Must be a valid Python+ identifier. `None` creates an unnamed cell. Names are reserved+ for special cases (for example, `"setup"`). Prefer the+ returned cell ID unless naming is important."""self._require_entered()if before is not None and after is not None:raise ValueError("Cannot specify both 'before' and 'after'")+ _validate_cell_name(name)cell_id, resolved_name = self._resolve_new_cell(name)config = CellConfig(@@ -1202,9 +1225,11 @@ class AsyncCodeModeContext:expand_output (bool, optional): Show the cell's output in fullinstead of clamping it to a fixed height. None keeps existing.column (int, optional): Column index for multi-column layouts. None keeps existing.- name (str, optional): New name for the cell. None keeps existing.+ name (str, optional): New name for the cell. Must be a valid Python+ identifier. `None` keeps the existing name."""self._require_entered()+ _validate_cell_name(name)cell_id = self._resolve_target(target)# Handle cell-id migration when converting to a setup cell.diff --git a/tests/_code_mode/test_code_mode_context.py b/tests/_code_mode/test_code_mode_context.pyindex e1ee10a430..1099ad56e6 100644--- a/tests/_code_mode/test_code_mode_context.py+++ b/tests/_code_mode/test_code_mode_context.py@@ -75,6 +75,52 @@ def _graph_codes(k: Kernel) -> dict[str, str]:class TestAddCell:+ @pytest.mark.parametrize(+ ("name", "expected_name"),+ [+ (None, ""),+ ("", ""),+ ("load_data", "load_data"),+ ("_private", "_private"),+ ("K", "K"),+ ("résumé", "résumé"),+ ("match", "match"),+ ],+ )+ async def test_accepts_valid_name(+ self, k: Kernel, name: str | None, expected_name: str+ ) -> None:+ with _ctx(k) as ctx:+ async with ctx as nb:+ nb.create_cell("x = 1", name=name)++ create = next(+ op for op in _tx_ops(k) if op["type"] == "create-cell"+ )+ assert create["name"] == expected_name++ @pytest.mark.parametrize(+ ("name", "message"),+ [+ ("Load data", "valid, non-keyword Python identifiers"),+ ("class", "valid, non-keyword Python identifiers"),+ ("segment-change", "valid, non-keyword Python identifiers"),+ ("123_cell", "valid, non-keyword Python identifiers"),+ ("_", "reserved for unnamed cells"),+ ("__", "reserved for unnamed cells"),+ ("K", "NFKC-normalized"),+ ],+ )+ async def test_rejects_invalid_name(+ self, k: Kernel, name: str, message: str+ ) -> None:+ with _ctx(k) as ctx:+ async with ctx as nb:+ with pytest.raises(ValueError, match=message):+ nb.create_cell("x = 1", name=name)++ assert not k.graph.cells+async def test_add_into_empty(self, k: Kernel) -> None:with _ctx(k) as ctx:_clear_messages(k)@@ -259,6 +305,53 @@ class TestDeleteCell:class TestUpdateCell:+ @pytest.mark.parametrize(+ "name", [None, "", "analysis_summary", "K", "résumé", "match"]+ )+ async def test_accepts_valid_name(+ self, k: Kernel, name: str | None+ ) -> None:+ await k.run([ExecuteCellCommand(cell_id=CellId_t("0"), code="x = 1")])++ with _ctx(k) as ctx:+ _clear_messages(k)+ async with ctx as nb:+ nb.edit_cell("0", name=name)++ name_ops = [op for op in _tx_ops(k) if op["type"] == "set-name"]+ if name is None:+ assert not name_ops+ else:+ assert name_ops == [+ {"type": "set-name", "cellId": "0", "name": name}+ ]++ @pytest.mark.parametrize(+ ("name", "message"),+ [+ ("Analysis summary", "valid, non-keyword Python identifiers"),+ ("for", "valid, non-keyword Python identifiers"),+ ("analysis-summary", "valid, non-keyword Python identifiers"),+ ("1st_cell", "valid, non-keyword Python identifiers"),+ ("_", "reserved for unnamed cells"),+ ("__", "reserved for unnamed cells"),+ ("K", "NFKC-normalized"),+ ],+ )+ async def test_rejects_invalid_name(+ self, k: Kernel, name: str, message: str+ ) -> None:+ await k.run([ExecuteCellCommand(cell_id=CellId_t("0"), code="x = 1")])++ with _ctx(k) as ctx:+ _clear_messages(k)+ async with ctx as nb:+ with pytest.raises(ValueError, match=message):+ nb.edit_cell("0", name=name)++ assert _graph_codes(k) == {"0": "x = 1"}+ assert not _tx_ops(k)+async def test_update_code(self, k: Kernel) -> None:await k.run([ExecuteCellCommand(cell_id=CellId_t("0"), code="x = 1")])assert k.globals["x"] == 1