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: align generated cell formatting with Ruff (#11441)
Dylan Madisetti38182e65c7b6
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex d7645635ac..4f3ccd81ec 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -141,21 +141,16 @@ def _needs_trailing_blank_line(mod: ast.Module, code: str) -> bool:if not mod.body:return Falselast_stmt = mod.body[-1]- if not isinstance(- last_stmt,- (- ast.Import,- ast.ImportFrom,- ast.FunctionDef,- ast.AsyncFunctionDef,- ast.ClassDef,- ),- ):- return False# Check if there's trailing content (like comments) after the last statement# If so, don't add a blank line - the existing formatting should be preservedcode_lines = code.rstrip().count("\n") + 1- return last_stmt.end_lineno == code_lines+ if isinstance(last_stmt, (ast.Import, ast.ImportFrom)):+ return last_stmt.end_lineno == code_lines+ return any(+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))+ and node.end_lineno == code_lines+ for node in ast.walk(last_stmt)+ )def _can_strip_bare_return(cell: CellImpl) -> bool:@@ -453,11 +448,13 @@ def generate_unparsable_cell(if name is not None:flags["name"] = name- kwargs = ", ".join(+ kwargs = ",\n".join([f"{key}={_format_arg(value)}" for key, value in flags.items()])if kwargs:- text.extend([indent_text(f"{code_as_str},"), indent_text(kwargs)])+ text.extend(+ [indent_text(f"{code_as_str},"), indent_text(f"{kwargs},")]+ )else:text.append(indent_text(code_as_str))diff --git a/marimo/_ast/parse.py b/marimo/_ast/parse.pyindex 8a85e40d89..978c64b22a 100644--- a/marimo/_ast/parse.py+++ b/marimo/_ast/parse.py@@ -354,9 +354,11 @@ class Extractor:new_end -= 1breakif new_end > end_lineno:- cell_code += "\n".join(+ trailing_code = "\n".join(self.lines[end_lineno : new_end + 1]).rstrip()+ if trailing_code:+ cell_code += "\n" + trailing_codeend_lineno = new_end - 1if end_col_offset is None:diff --git a/tests/_ast/codegen_data/test_generate_filecontents_with_syntax_error.py b/tests/_ast/codegen_data/test_generate_filecontents_with_syntax_error.pyindex 6e99a9f508..f3817ef7e9 100644--- a/tests/_ast/codegen_data/test_generate_filecontents_with_syntax_error.py+++ b/tests/_ast/codegen_data/test_generate_filecontents_with_syntax_error.py@@ -13,7 +13,7 @@ app._unparsable_cell(r"""_ error""",- name="two"+ name="two",)@@ -29,7 +29,7 @@ app._unparsable_cell(\\t""",- name="_"+ name="_",)diff --git a/tests/_ast/codegen_data/test_unparsable_cell_with_triple_quotes.py b/tests/_ast/codegen_data/test_unparsable_cell_with_triple_quotes.pyindex 82378e014b..8f7a68ed63 100644--- a/tests/_ast/codegen_data/test_unparsable_cell_with_triple_quotes.py+++ b/tests/_ast/codegen_data/test_unparsable_cell_with_triple_quotes.py@@ -15,7 +15,7 @@ app._unparsable_cell(```python {.marimo}print(\"Hello, World!\")""",- name="_"+ name="_",)@@ -23,7 +23,7 @@ app._unparsable_cell(r"""it's an unparsable cell""",- name="_"+ name="_",)diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex 91d56075fa..dcc57d84f2 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -274,7 +274,7 @@ app._unparsable_cell(r"""x = 1""",- name="my_cell"+ name="my_cell",)\''')@@ -336,7 +336,11 @@ app._unparsable_cell(r"""x = 1""",- column=1, disabled=True, hide_code=True, expand_output=True, name="named_cell"+ column=1,+ disabled=True,+ hide_code=True,+ expand_output=True,+ name="named_cell",)\''')diff --git a/tests/_cli/test_cli_check.py b/tests/_cli/test_cli_check.pyindex 8f65115644..21d208c2f7 100644--- a/tests/_cli/test_cli_check.py+++ b/tests/_cli/test_cli_check.py@@ -2,13 +2,82 @@"""CLI tests for the marimo check command."""import json+import subprocess+import sysimport tempfile+from pathlib import Path+import pytestfrom click.testing import CliRunner+from marimo._ast.cell import CellConfig+from marimo._ast.codegen import generate_filecontentsfrom marimo._cli.cli import check+ ("code", "config", "exit_code"),+ [+ pytest.param(+ "if True:\n\n def f():\n pass",+ CellConfig(),+ 0,+ id="nested_function",+ ),+ pytest.param(+ "if True:\n\n async def f():\n pass",+ CellConfig(),+ 0,+ id="nested_async_function",+ ),+ pytest.param(+ "if True:\n\n class Foo:\n pass",+ CellConfig(),+ 0,+ id="nested_class",+ ),+ pytest.param(+ "if True:\n\n def f():\n pass\n\n# trailing comment",+ CellConfig(),+ 0,+ id="trailing_comment",+ ),+ pytest.param("a =", CellConfig(), 1, id="unparsable"),+ pytest.param(+ "a =",+ CellConfig(disabled=True, hide_code=True),+ 1,+ id="unparsable_with_config",+ ),+ ],+)+def test_fix_preserves_ruff_formatting(+ tmp_path: Path, code: str, config: CellConfig, exit_code: int+) -> None:+ path = tmp_path / "notebook.py"+ path.write_text(generate_filecontents([code], ["_"], [config]))+ subprocess.run(+ [+ sys.executable,+ "-m",+ "ruff",+ "format",+ "--isolated",+ "--line-length=79",+ str(path),+ ],+ check=True,+ capture_output=True,+ text=True,+ )+ formatted = path.read_text()++ result = CliRunner().invoke(check, [str(path), "--fix"])++ assert result.exit_code == exit_code, result.output+ assert path.read_text() == formatted++class TestLintCLI:"""Test the check CLI command."""diff --git a/tests/_convert/ipynb/snapshots/converted_duplicate_definitions_syntax_error.py.txt b/tests/_convert/ipynb/snapshots/converted_duplicate_definitions_syntax_error.py.txtindex 89afb354f2..5dfa56f072 100644--- a/tests/_convert/ipynb/snapshots/converted_duplicate_definitions_syntax_error.py.txt+++ b/tests/_convert/ipynb/snapshots/converted_duplicate_definitions_syntax_error.py.txt@@ -7,7 +7,7 @@ app._unparsable_cell(r"""x ( b 2 d & !""",- name="_"+ name="_",)diff --git a/tests/_convert/markdown/snapshots/unsafe-doc.py.txt b/tests/_convert/markdown/snapshots/unsafe-doc.py.txtindex 04e59da1ee..d7d341c366 100644--- a/tests/_convert/markdown/snapshots/unsafe-doc.py.txt+++ b/tests/_convert/markdown/snapshots/unsafe-doc.py.txt@@ -34,7 +34,7 @@ app._unparsable_cell(r"""it's an unparsable cell""",- name="_"+ name="_",)@@ -91,7 +91,7 @@ app._unparsable_cell(```python {.marimo}print(\"Hello, World!\")""",- name="_"+ name="_",)diff --git a/tests/_convert/snapshots/unparsable_cell_with_escaped_quotes.py.txt b/tests/_convert/snapshots/unparsable_cell_with_escaped_quotes.py.txtindex 10bc1d9d87..9e4d3f0c5e 100644--- a/tests/_convert/snapshots/unparsable_cell_with_escaped_quotes.py.txt+++ b/tests/_convert/snapshots/unparsable_cell_with_escaped_quotes.py.txt@@ -8,7 +8,7 @@ app._unparsable_cell(r"""return""",- name="_"+ name="_",)@@ -18,7 +18,7 @@ app._unparsable_cell(x = "hello \"world\"x.""",- name="_"+ name="_",)@@ -28,7 +28,7 @@ app._unparsable_cell(x = "hello \"\"\"world\"\"\""x.""",- name="_"+ name="_",)@@ -39,7 +39,7 @@ app._unparsable_cell(path = "C:\\Users\\test"x.""",- name="_"+ name="_",)diff --git a/tests/_convert/test_convert_py.py b/tests/_convert/test_convert_py.pyindex eabb782edc..8b7987b73f 100644--- a/tests/_convert/test_convert_py.py+++ b/tests/_convert/test_convert_py.py@@ -148,9 +148,10 @@ def test_unparsable_cell_with_escaped_quotes():def identity(x: str) -> str:return MarimoConvert.from_py(x).to_py()- assert identity(marimo_script) == marimo_script- assert identity(identity(marimo_script)) == marimo_script- assert identity(identity(identity(marimo_script))) == marimo_script+ expected = marimo_script.replace(' name="_"\n', ' name="_",\n')+ assert identity(marimo_script) == expected+ assert identity(identity(marimo_script)) == expected+ assert identity(identity(identity(marimo_script))) == expectedsnapshot("unparsable_cell_with_escaped_quotes.py.txt", identity(marimo_script))