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.

mep/8: Formatting for library serialization (#4333)

Dylan Madisetti9f26385f07d1
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.py
index 9195741114..1084f48466 100644
--- a/marimo/_ast/cell_manager.py
+++ b/marimo/_ast/cell_manager.py
@@ -212,6 +212,13 @@ class CellManager:
name: Optional name for the cell
cell_config: Configuration for the cell
"""
+ # If this is the first cell, and its name is setup, assume that it's
+ # the setup cell.
+ if len(self._cell_data) == 0 and name == SETUP_CELL_NAME:
+ cell_id = CellId_t(SETUP_CELL_NAME)
+ else:
+ cell_id = self.create_cell_id()
+
# - code.split("\n")[1:-1] disregards first and last lines, which are
# empty
# - line[4:] removes leading indent in multiline string
@@ -222,7 +229,7 @@ class CellManager:
)
self.register_cell(
- cell_id=self.create_cell_id(),
+ cell_id=cell_id,
code=code,
config=cell_config,
name=name or DEFAULT_CELL_NAME,
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 10b6c511f2..ae3ddc8841 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -31,7 +31,7 @@ NOTICE = "\n".join(
)
-def get_setup_cell(
+def pop_setup_cell(
code: list[str],
names: list[str],
configs: list[CellConfig],
@@ -41,12 +41,16 @@ def get_setup_cell(
if SETUP_CELL_NAME not in names or not toplevel_fn:
return None
setup_index = names.index(SETUP_CELL_NAME)
- setup_code = code.pop(setup_index)
+ try:
+ cell = compile_cell(
+ code[setup_index], cell_id=CellId_t(SETUP_CELL_NAME)
+ ).configure(configs[setup_index])
+ except SyntaxError:
+ return None
+ code.pop(setup_index)
names.pop(setup_index)
- setup_config = configs.pop(setup_index)
- return compile_cell(
- setup_code, cell_id=CellId_t(SETUP_CELL_NAME)
- ).configure(setup_config)
+ configs.pop(setup_index)
+ return cell
def indent_text(text: str) -> str:
@@ -136,6 +140,7 @@ def build_setup_section(setup_cell: Optional[CellImpl]) -> str:
[
"with app.setup:",
indent_text(block),
+ "\n",
]
)
@@ -230,7 +235,7 @@ def generate_unparsable_cell(
return "\n".join(text)
-def serialize(
+def serialize_cell(
extraction: TopLevelExtraction, status: TopLevelStatus, toplevel_fn: bool
) -> str:
if status.is_unparsable:
@@ -247,7 +252,10 @@ def serialize(
return to_functiondef(
cell,
status.name,
- extraction.allowed_refs,
+ # There are possible NameError cases where a cell defines and also
+ # requires a variable. We remove defs from the signature such that
+ # this causes a lint error in programs like pyright.
+ extraction.allowed_refs | cell.defs,
extraction.used_refs,
fn="cell",
)
@@ -322,13 +330,14 @@ def generate_filecontents(
names[idx] = DEFAULT_CELL_NAME
# TODO: replace with dedicated cell
- setup_cell = get_setup_cell(codes, names, cell_configs, toplevel_fn)
+ setup_cell = pop_setup_cell(codes, names, cell_configs, toplevel_fn)
toplevel_defs: set[Name] = set()
if setup_cell:
toplevel_defs = set(setup_cell.defs)
extraction = TopLevelExtraction(codes, names, cell_configs, toplevel_defs)
cell_blocks = [
- serialize(extraction, status, toplevel_fn) for status in extraction
+ serialize_cell(extraction, status, toplevel_fn)
+ for status in extraction
]
if not toplevel_fn:
@@ -346,7 +355,6 @@ def generate_filecontents(
generate_app_constructor(config),
"",
build_setup_section(setup_cell),
- "\n",
"\n\n\n".join(cell_blocks),
"\n",
'if __name__ == "__main__":',
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index 89dd3c1eca..c055e713c3 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -67,6 +67,9 @@ def ends_with_semicolon(code: str) -> bool:
token_types.NEWLINE,
token_types.NL,
token_types.COMMENT,
+ token_types.INDENT,
+ token_types.DEDENT,
+ token_types.ENCODING,
):
continue
return token.string == ";"
diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.py
index 041c94f7de..85d7ffb215 100644
--- a/marimo/_ast/toplevel.py
+++ b/marimo/_ast/toplevel.py
@@ -2,7 +2,10 @@
from __future__ import annotations
import builtins
+import token as token_types
from enum import Enum
+from io import BytesIO
+from tokenize import tokenize
from typing import TYPE_CHECKING, Literal, Optional, Union, get_args
from marimo._ast.app import InternalApp
@@ -25,6 +28,7 @@ TopLevelInvalidHints = Literal[
"Signature and decorators depend on {} defined out of correct cell order",
"Function contains references to variables {} which are not top level.",
"Function contains references to variables {} which failed to be toplevel.",
+ "Cell cannot contain non-indented trailing comments.",
]
(
HINT_UNPARSABLE,
@@ -33,12 +37,30 @@ TopLevelInvalidHints = Literal[
HINT_ORDER_DEPENDENT,
HINT_HAS_REFS,
HINT_HAS_CLOSE_REFS,
+ HINT_HAS_COMMENT,
) = get_args(TopLevelInvalidHints)
TopLevelHints = Union[Literal["Valid"], TopLevelInvalidHints]
HINT_VALID, *_ = get_args(TopLevelHints)
+def has_trailing_comment(code: str) -> bool:
+ # Requires tokenization because multiline strings can start a line with #.
+ tokens = tokenize(BytesIO(code.strip().encode("utf-8")).readline)
+ for token in reversed(list(tokens)):
+ if token.type in (
+ token_types.ENDMARKER,
+ token_types.NEWLINE,
+ token_types.NL,
+ token_types.INDENT,
+ token_types.DEDENT,
+ token_types.ENCODING,
+ ):
+ continue
+ return token.type == token_types.COMMENT and token.start[1] == 0
+ return False
+
+
class TopLevelType(Enum):
CELL = "cell"
TOPLEVEL = "toplevel"
@@ -109,6 +131,12 @@ class TopLevelStatus:
self.demote(HINT_BAD_NAME)
return
+ # Trailing comments are not allowed, since no easy way to recapture
+ # them.
+ if has_trailing_comment(self.code):
+ self.demote(HINT_HAS_COMMENT)
+ return
+
allowed_refs = set(allowed_refs) | {self.name}
order_dependent_refs = var.unbounded_refs - allowed_refs
if order_dependent_refs and order_dependent_refs - unresolved:
@@ -302,9 +330,9 @@ class TopLevelExtraction:
names = ["_" for cell in cells]
cell_configs = [cell.config for cell in cells]
- from marimo._ast.codegen import get_setup_cell
+ from marimo._ast.codegen import pop_setup_cell
- setup = get_setup_cell(codes, names, cell_configs, True)
+ setup = pop_setup_cell(codes, names, cell_configs, True)
if setup:
return cls(codes, names, cell_configs, setup.defs)
return cls(codes, names, cell_configs, set())
@@ -315,9 +343,9 @@ class TopLevelExtraction:
names = list(app.cell_manager.names())
cell_configs = list(app.cell_manager.configs())
- from marimo._ast.codegen import get_setup_cell
+ from marimo._ast.codegen import pop_setup_cell
- setup = get_setup_cell(codes, names, cell_configs, True)
+ setup = pop_setup_cell(codes, names, cell_configs, True)
if setup:
return cls(codes, names, cell_configs, setup.defs)
return cls(codes, names, cell_configs, set())
diff --git a/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py b/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py
index effee8a077..c4ea10080a 100644
--- a/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py
+++ b/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py
@@ -46,7 +46,6 @@ def shadow_case(shadow):
def _(shadow):
def reference_case():
return shadow
-
return
@@ -55,7 +54,6 @@ def _(globe):
def global_case():
global globe
return globe
-
return
@@ -74,5 +72,22 @@ def fun_that_uses_another():
return fun_that_uses_mo()
+def cell_with_ref_and_def():
+ if mo is None:
+ var = maybe
+ maybe = 1
+ return (maybe,)
+
+
+def _():
+ # Trailing comments should break function serialization.
+ def addition_with_trailing_comments(a, b):
+ return a + b
+ # This is a comment
+ return
+
+
if __name__ == "__main__":
app.run()
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 0e986e1b61..b4f3d3f843 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -76,6 +76,48 @@ class TestApp:
assert (defs["y"], defs["z"]) == (1, 2)
assert defs["a"] == 2
+ @staticmethod
+ def test_setup() -> None:
+ app = App()
+
+ with app.setup:
+ x = 0
+ x
+
+ @app.cell
+ def two(z: int) -> tuple[int]:
+ a = x + z
+ a + 1
+ return (a,)
+
+ @app.cell
+ def __() -> tuple[int, int]:
+ y = x + 1
+ z = y + 1
+ return y, z
+
+ cell_manager = app._cell_manager
+ cell_names = tuple(cell_manager.names())
+ assert cell_names[0] == "setup"
+ assert cell_names[1] == "two"
+ assert cell_names[2] == "__"
+
+ codes = tuple(cell_manager.codes())
+ assert codes[0] == "x = 0\nx"
+ assert codes[1] == "a = x + z\na + 1"
+ assert codes[2] == "y = x + 1\nz = y + 1"
+
+ outputs, defs = app.run()
+
+ assert outputs[0] == defs["x"]
+ assert outputs[1] == defs["a"] + 1
+ assert outputs[2] is None
+
+ assert defs["x"] == 0
+ assert (defs["y"], defs["z"]) == (1, 2)
+ assert defs["a"] == 2
+
+
@staticmethod
def test_cycle() -> None:
app = App()
@@ -606,6 +648,38 @@ class TestApp:
)
+class TestInvalidSetup:
+ @staticmethod
+ def test_initial_setup() -> None:
+ app = App()
+ app._unparsable_cell(";",
+ name="setup")
+
+ assert app._cell_manager.has_cell("setup")
+ assert app._cell_manager.cell_name("setup") == "setup"
+
+ @staticmethod
+ def test_not_initial_setup() -> None:
+ app = App()
+ app._unparsable_cell(";",
+ name="other")
+ app._unparsable_cell(";",
+ name="setup")
+
+ assert not app._cell_manager.has_cell("setup")
+
+ @staticmethod
+ def test_not_initial_setup_cell() -> None:
+ app = App()
+ @app.cell
+ def _():
+ def B() -> float:
+ return 1.0
+ app._unparsable_cell(";",
+ name="setup")
+ assert not app._cell_manager.has_cell("setup")
+
+
def test_app_config() -> None:
config = _AppConfig.from_untrusted_dict({"width": "full"})
assert config.width == "full"
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index 4f7786c102..4fbee9d06e 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -66,10 +66,6 @@ def wrap_generate_filecontents(
)
-def strip_blank_lines(text: str) -> str:
- return "\n".join([line for line in text.splitlines() if line.strip()])
-
-
def get_idempotent_marimo_source(name: str) -> str:
from marimo._utils.formatter import Formatter
@@ -89,15 +85,11 @@ def get_idempotent_marimo_source(name: str) -> str:
with open(path) as f:
python_source = sanitized_version(f.read())
- # TODO(dmadisetti): not totally idempotent for now. Revise; seems to strip
- # on imports (possibly during compile?).
formatted = Formatter(codegen.MAX_LINE_LENGTH).format(
{"source": python_source, "generated": generated_contents}
)
- assert strip_blank_lines(formatted["source"]) == strip_blank_lines(
- formatted["generated"]
- )
+ assert formatted["source"] == formatted["generated"]
return formatted["generated"]
diff --git a/tests/_ast/test_toplevel.py b/tests/_ast/test_toplevel.py
index 732389d5b7..f5a433ae4f 100644
--- a/tests/_ast/test_toplevel.py
+++ b/tests/_ast/test_toplevel.py
@@ -142,6 +142,38 @@ class TestTopLevelExtraction:
extraction = TopLevelExtraction.from_app(InternalApp(app))
assert [TopLevelType.TOPLEVEL] == [s.type for s in extraction]
+ @staticmethod
+ def test_function_trailing_comment(app) -> None:
+ @app.cell
+ def cell():
+ def add(a: int, b: int) -> float:
+ return a + b
+
+ # Comment
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [TopLevelType.CELL] == [s.type for s in extraction]
+ assert extraction.statuses[0].hint == toplevel.HINT_HAS_COMMENT
+
+ @staticmethod
+ def test_function_trailing_comment_ok(app) -> None:
+ @app.cell
+ def cell():
+ def add(a: int, b: int) -> float:
+ return a + b
+ # Comment
+
+ @app.cell
+ def tricky_cell():
+ def md() -> float:
+ return """
+ #"""
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [TopLevelType.TOPLEVEL, TopLevelType.TOPLEVEL] == [
+ s.type for s in extraction
+ ]
+
@staticmethod
def test_function_uses_top_fn_unresolved(app) -> None:
@app.cell