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
bug: formatting of exposed classes preserves class decorators (#10042)
Yair Chuchem3b2f21a540cc
diff --git a/marimo/_ast/parse.py b/marimo/_ast/parse.pyindex 5eff55ea55..574305349d 100644--- a/marimo/_ast/parse.py+++ b/marimo/_ast/parse.py@@ -99,9 +99,19 @@ def unwrap_cell_body(formatted: str) -> str:)if fn.end_lineno is None:raise ValueError("FunctionDef node has no end_lineno")+ first = fn.body[0]+ start_lineno = first.lineno - 1+ # AST statement line numbers point at `def`/`class`, not decorators.+ # Start at the first decorator to preserve decorated top-level cells.+ if isinstance(+ first, (ast.AsyncFunctionDef, ast.FunctionDef, ast.ClassDef)+ ):+ if first.decorator_list:+ start_lineno = first.decorator_list[0].lineno - 1+extractor = Extractor(formatted)raw = extractor.extract_from_offsets(- fn.body[0].lineno - 1, 0, fn.end_lineno - 1, fn.end_col_offset+ start_lineno, 0, fn.end_lineno - 1, fn.end_col_offset)return fixed_dedent(raw).strip()diff --git a/tests/_utils/test_formatter.py b/tests/_utils/test_formatter.pyindex b8a51d8118..b432d3c7db 100644--- a/tests/_utils/test_formatter.py+++ b/tests/_utils/test_formatter.py@@ -216,6 +216,27 @@ class TestRuffFormatter:assert result == {"cell1": 'def foo():\n """Something here"""'}+ @patch("marimo._utils.formatter.ruff")+ async def test_ruff_formatter_preserves_class_decorator(+ self, mock_ruff: MagicMock+ ) -> None:+ cell_code = (+ "@dataclasses.dataclass\nclass Test:\n name: str\n age: int"+ )+ wrapped_formatted = (+ "def _():\n"+ " @dataclasses.dataclass\n"+ " class Test:\n"+ " name: str\n"+ " age: int"+ )+ mock_ruff.return_value = {"cell1": wrapped_formatted}++ formatter = RuffFormatter(line_length=88)+ result = await formatter.format({"cell1": cell_code})++ assert result == {"cell1": cell_code}+@patch("marimo._utils.formatter.ruff")async def test_ruff_formatter_comment_only_cell(self, mock_ruff: MagicMock