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.

chore: typesafe CellId (#3844)

Myles Scolnickade6292517dd
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index be5c8d61d7..7ed6b9fa47 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -576,6 +576,8 @@ class App:
# that defined the name bound to this App, if any
app_kernel_runner = self._get_kernel_runner()
+ outputs: dict[CellId_t, Any]
+ glbls: dict[str, Any]
if not app_kernel_runner.outputs:
outputs, glbls = await app_kernel_runner.run(
set(self._execution_order)
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 3744c41526..d9edfe0774 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -17,6 +17,7 @@ from marimo._ast.compiler import compile_cell
from marimo._ast.names import DEFAULT_CELL_NAME
from marimo._ast.transformers import RemoveImportTransformer
from marimo._ast.visitor import Name
+from marimo._types.ids import CellId_t
INDENT = " "
MAX_LINE_LENGTH = 80
@@ -124,13 +125,15 @@ def build_import_section(import_blocks: list[str]) -> str:
]
)
- formatted = Formatter(MAX_LINE_LENGTH).format({"code": code})
+ stub_cell_id = CellId_t("sub")
+
+ formatted = Formatter(MAX_LINE_LENGTH).format({stub_cell_id: code})
if not formatted:
return code
tidied = ruff(formatted, "check", "--fix-only")
if not tidied:
- return formatted["code"]
- return tidied["code"] + "\n\n"
+ return formatted[stub_cell_id]
+ return tidied[stub_cell_id] + "\n\n"
def to_functiondef(
@@ -301,7 +304,9 @@ def generate_filecontents(
cell: Optional[CellImpl]
for idx, (code, cell_config) in enumerate(zip(codes, cell_configs)):
try:
- cell = compile_cell(code, cell_id=str(idx)).configure(cell_config)
+ cell = compile_cell(code, cell_id=CellId_t(str(idx))).configure(
+ cell_config
+ )
defs |= cell.defs
assert isinstance(used_refs, set)
used_refs |= cell.refs
diff --git a/marimo/_convert/ipynb.py b/marimo/_convert/ipynb.py
index 07e0381bde..fc2e0a8306 100644
--- a/marimo/_convert/ipynb.py
+++ b/marimo/_convert/ipynb.py
@@ -15,6 +15,7 @@ from marimo._ast.variables import is_local
from marimo._ast.visitor import Block, NamedNode, ScopedVisitor
from marimo._convert.utils import generate_from_sources, markdown_to_marimo
from marimo._runtime.dataflow import DirectedGraph
+from marimo._types.ids import CellId_t
# Define a type for our transform functions
Transform = Callable[[List[str]], List[str]]
@@ -30,7 +31,7 @@ def transform_fixup_multiple_definitions(sources: List[str]) -> List[str]:
"""
try:
cells = [
- compile_cell(source, cell_id=str(i))
+ compile_cell(source, cell_id=CellId_t(str(i)))
for i, source in enumerate(sources)
]
except SyntaxError:
diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.py
index b850ef5d3c..acd17317b9 100644
--- a/marimo/_islands/_island_generator.py
+++ b/marimo/_islands/_island_generator.py
@@ -18,6 +18,7 @@ from marimo._plugins.ui import code_editor
from marimo._server.export import run_app_until_completion
from marimo._server.file_manager import AppFileManager
from marimo._server.file_router import AppFileRouter
+from marimo._types.ids import CellId_t
from marimo._utils.marimo_path import MarimoPath
if sys.platform == "win32": # handling for windows
@@ -40,7 +41,7 @@ class MarimoIslandStub:
app_id: str,
code: str,
):
- self._cell_id = cell_id
+ self._cell_id = CellId_t(cell_id)
self._app_id = app_id
self._code = code
self._display_code = display_code
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
index 6f8a2e0e2d..bad6c85999 100644
--- a/marimo/_runtime/app/kernel_runner.py
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -108,7 +108,7 @@ class AppKernelRunner:
return self._outputs
@property
- def globals(self) -> dict[CellId_t, Any]:
+ def globals(self) -> dict[str, Any]:
return self._kernel.globals
async def run(self, cells_to_run: set[CellId_t]) -> RunOutput:
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 89d95c92c5..2353daa4a4 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -43,6 +43,7 @@ from marimo._save.loaders import (
LoaderType,
MemoryLoader,
)
+from marimo._types.ids import CellId_t
# Many assertions are for typing and should always pass. This message is a
# catch all to motive users to report if something does fail.
@@ -131,7 +132,7 @@ class _cache_call(object):
# defined out of the context of the block, or the cell.
# For instance, the args of the invoked function are restricted to the
# block.
- cell_id = ctx.cell_id or ctx.execution_context.cell_id or ""
+ cell_id = ctx.cell_id or ctx.execution_context.cell_id or CellId_t("")
self.scoped_refs = set([f"{ARG_PREFIX}{k}" for k in self._args])
# As are the "locals" not in globals
self.scoped_refs |= set(f_locals.keys()) - set(ctx.globals.keys())
diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.py
index f230d18cb7..99ddff44ff 100644
--- a/marimo/_server/api/endpoints/ws.py
+++ b/marimo/_server/api/endpoints/ws.py
@@ -199,7 +199,7 @@ async def ycell_provider(
await websocket.close(WebSocketCodes.FORBIDDEN, "MARIMO_NOT_ALLOWED")
return
await websocket.accept()
- cell_id: str = websocket.path_params["cell_id"]
+ cell_id = CellId_t(websocket.path_params["cell_id"])
key = CellIdAndFileKey(cell_id, file_key)
async with ycell_lock:
if key in ycells:
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index baccebc524..5c9e55d163 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -292,7 +292,7 @@ class Exporter:
if not cell or cell._cell.language == "sql":
try:
cell_impl = compile_cell(
- code, cell_id=str(cell_data.cell_id)
+ code, cell_id=cell_data.cell_id
).configure(cell_data.config)
cell = Cell(
_cell=cell_impl,
diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.py
index 941ef139fd..9d97461aad 100644
--- a/marimo/_server/session/serialize.py
+++ b/marimo/_server/session/serialize.py
@@ -25,6 +25,7 @@ from marimo._schemas.session import (
StreamOutput,
)
from marimo._server.session.session_view import SessionView
+from marimo._types.ids import CellId_t
from marimo._utils.background_task import AsyncBackgroundTask
from marimo._utils.lists import as_list
@@ -158,8 +159,10 @@ def deserialize_session(session: NotebookSessionV1) -> SessionView:
)
)
- view.cell_operations[cell["id"]] = CellOp(
- cell_id=cell["id"],
+ cell_id = CellId_t(cell["id"])
+
+ view.cell_operations[cell_id] = CellOp(
+ cell_id=cell_id,
status="idle",
output=cell_outputs[0] if cell_outputs else None,
console=console_outputs,
diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.py
index e3d9b7b498..5a2182d172 100644
--- a/marimo/_server/templates/templates.py
+++ b/marimo/_server/templates/templates.py
@@ -103,7 +103,7 @@ def static_notebook_template(
filepath: Optional[str],
code: str,
code_hash: str,
- cell_ids: list[str],
+ cell_ids: list[CellId_t],
cell_names: list[str],
cell_codes: list[str],
cell_configs: list[CellConfig],
diff --git a/marimo/_types/ids.py b/marimo/_types/ids.py
index 9329f8b208..57700b4688 100644
--- a/marimo/_types/ids.py
+++ b/marimo/_types/ids.py
@@ -2,9 +2,7 @@ from __future__ import annotations
from typing import NewType
-# TODO: enable NewType for better type checking
-# CellId_t = NewType("CellId_t", str)
-CellId_t = str
+CellId_t = NewType("CellId_t", str)
UIElementId = NewType("UIElementId", str)
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index da45db17b4..607ba9935a 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -30,7 +30,7 @@ from marimo._server.session.session_view import SessionView
from marimo._types.ids import CellId_t
from marimo._utils.parse_dataclass import parse_raw
-cell_id: CellId_t = "cell_1"
+cell_id = CellId_t("cell_1")
initial_output = CellOutput(
channel=CellChannel.OUTPUT,