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.

feat: add `--unsafe-fixes` and example rule (#6398)

Dylan Madisettiadc50a1dc56b
diff --git a/docs/guides/lint_rules/index.md b/docs/guides/lint_rules/index.md
index a5ef3199a8..804a97a174 100644
--- a/docs/guides/lint_rules/index.md
+++ b/docs/guides/lint_rules/index.md
@@ -42,10 +42,12 @@ These are style and formatting issues.
| [MF001](rules/general_formatting.md) | general-formatting | General formatting issues with the notebook format. | 🛠️ |
| [MF002](rules/parse_stdout.md) | parse-stdout | Parse captured stdout during notebook loading | ❌ |
| [MF003](rules/parse_stderr.md) | parse-stderr | Parse captured stderr during notebook loading | ❌ |
+| [MF004](rules/empty_cells.md) | empty-cells | Empty cells that can be safely removed. | ⚠️ |
## Legend
- 🛠️ = Automatically fixable with `marimo check --fix`
+- ⚠️ = Fixable with `marimo check --fix --unsafe-fixes` (may change code behavior)
- ❌ = Not automatically fixable
## Configuration
diff --git a/docs/guides/lint_rules/rules/empty_cells.md b/docs/guides/lint_rules/rules/empty_cells.md
new file mode 100644
index 0000000000..7e55c64a60
--- /dev/null
+++ b/docs/guides/lint_rules/rules/empty_cells.md
@@ -0,0 +1,62 @@
+# MF004: empty-cells
+
+✨ **Formatting** ⚠️ Unsafe Fixable
+
+MF004: Empty cells that can be safely removed.
+
+## What it does
+
+Detects cells that contain only:
+- Whitespace characters (spaces, tabs, newlines)
+- Comments (lines starting with #)
+- Pass statements (`pass`)
+- Any combination of the above
+
+## Why is this bad?
+
+Empty cells can:
+- Create clutter in notebook structure
+- Add unnecessary complexity to the execution graph
+- Make notebooks harder to read and maintain
+- Increase file size without adding value
+
+While not functionally breaking, removing empty cells improves code
+clarity and reduces visual noise.
+
+## Examples
+
+**Problematic:**
+```python
+# Cell 1: Only whitespace
+```
+
+**Problematic:**
+```python
+# Cell 2: Only comments
+# This is just a comment
+# Nothing else here
+```
+
+**Problematic:**
+```python
+# Cell 3: Only pass statement
+pass
+```
+
+**Problematic:**
+```python
+# Cell 4: Mix of comments, whitespace, and pass
+# Some comment
+
+pass
+# Another comment
+```
+
+**Note:** This fix requires `--unsafe-fixes` because removing cells changes
+the notebook structure, and potentially removes user-intended content.
+
+## References
+
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+- [Best Practices](https://docs.marimo.io/guides/best_practices/)
+
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 5eea6722e4..76431b3b51 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -1247,9 +1247,21 @@ def shell_completion() -> None:
type=bool,
help="Whether to print detailed messages.",
)
+ "--unsafe-fixes",
+ is_flag=True,
+ default=False,
+ show_default=True,
+ type=bool,
+ help="Enable fixes that may change code behavior (e.g., removing empty cells).",
+)
@click.argument("files", nargs=-1, type=click.UNPROCESSED)
def check(
- fix: bool, strict: bool, verbose: bool, files: tuple[str, ...]
+ fix: bool,
+ strict: bool,
+ verbose: bool,
+ unsafe_fixes: bool,
+ files: tuple[str, ...],
) -> None:
if not files:
# If no files are provided, we lint the current directory
@@ -1257,7 +1269,7 @@ def check(
# Pass click.echo directly as pipe for streaming output, or None
pipe = click.echo if verbose else None
- linter = run_check(files, pipe=pipe, fix=fix)
+ linter = run_check(files, pipe=pipe, fix=fix, unsafe_fixes=unsafe_fixes)
# Get counts from linter (fix happens automatically during streaming)
fixed = linter.fixed_count
diff --git a/marimo/_lint/__init__.py b/marimo/_lint/__init__.py
index 0d8d12d522..b2801be553 100644
--- a/marimo/_lint/__init__.py
+++ b/marimo/_lint/__init__.py
@@ -17,6 +17,7 @@ def run_check(
file_patterns: tuple[str, ...],
pipe: Callable[[str], None] | None = None,
fix: bool = False,
+ unsafe_fixes: bool = False,
) -> Linter:
"""Run linting checks on files matching patterns (CLI entry point).
@@ -27,6 +28,7 @@ def run_check(
file_patterns: Glob patterns for file discovery
pipe: Optional function to call for streaming output
fix: Whether to fix files automatically
+ unsafe_fixes: Whether to enable unsafe fixes that may change behavior
Returns:
Linter with per-file status and diagnostics
@@ -34,7 +36,7 @@ def run_check(
# Expand patterns to actual files
files_to_check = expand_file_patterns(file_patterns)
- linter = Linter(pipe=pipe, fix_files=fix)
+ linter = Linter(pipe=pipe, fix_files=fix, unsafe_fixes=unsafe_fixes)
linter.run_streaming(files_to_check)
return linter
diff --git a/marimo/_lint/diagnostic.py b/marimo/_lint/diagnostic.py
index 4e37bdec91..95a2dec2c4 100644
--- a/marimo/_lint/diagnostic.py
+++ b/marimo/_lint/diagnostic.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from typing import Optional, cast
+from typing import Literal, Optional, cast
from marimo._types.ids import CellId_t
@@ -32,7 +32,7 @@ class Diagnostic:
code: Optional[str] = None
name: Optional[str] = None
severity: Optional[Severity] = None
- fixable: Optional[bool] = None
+ fixable: bool | Literal["unsafe"] | None = None
fix: Optional[str] = None
filename: Optional[str] = None
diff --git a/marimo/_lint/linter.py b/marimo/_lint/linter.py
index 92366037bf..4c9cb5ed20 100644
--- a/marimo/_lint/linter.py
+++ b/marimo/_lint/linter.py
@@ -47,12 +47,17 @@ class Linter:
early_stopping: EarlyStoppingConfig | None = None,
pipe: Callable[[str], None] | None = None,
fix_files: bool = False,
+ unsafe_fixes: bool = False,
):
self.rule_engine = RuleEngine.create_default(early_stopping)
self.pipe = pipe
self.fix_files = fix_files
+ self.unsafe_fixes = unsafe_fixes
self.files: list[FileStatus] = []
+ # Create rule lookup for unsafe fixes
+ self.rule_lookup = {rule.code: rule for rule in self.rule_engine.rules}
+
# File processing state
self.errored: bool = False
@@ -159,7 +164,11 @@ class Linter:
def _pipe_file_status(self, file_status: FileStatus) -> None:
"""Send file status through pipe for real-time output."""
for diagnostic in file_status.diagnostics:
- if not (self.fix_files and diagnostic.fixable):
+ will_fix = self.fix_files and (
+ diagnostic.fixable is True
+ or (diagnostic.fixable == "unsafe" and self.unsafe_fixes)
+ )
+ if not will_fix:
self.issues_count += 1
if not self.pipe:
@@ -178,6 +187,18 @@ class Linter:
self.pipe(diagnostic.format())
self.pipe("") # Empty line for spacing
+ @staticmethod
+ def _generate_file_contents_from_notebook(
+ notebook: NotebookSerialization, filename: str
+ ) -> str:
+ """Generate file contents from notebook serialization."""
+ converter = MarimoConvert.from_ir(notebook)
+
+ if filename.endswith((".md", ".qmd")):
+ return converter.to_markdown(filename)
+ else:
+ return converter.to_py()
+
@staticmethod
def _generate_file_contents(file_status: FileStatus) -> str:
"""Generate file contents from notebook serialization."""
@@ -186,12 +207,9 @@ class Linter:
"Cannot generate contents for file without notebook"
)
- converter = MarimoConvert.from_ir(file_status.notebook)
-
- if file_status.file.endswith((".md", ".qmd")):
- return converter.to_markdown(file_status.file)
- else:
- return converter.to_py()
+ return Linter._generate_file_contents_from_notebook(
+ file_status.notebook, file_status.file
+ )
def run_streaming(self, files_to_check: list[Path]) -> None:
"""Run linting checks with real-time streaming output."""
@@ -220,8 +238,7 @@ class Linter:
self.pipe(f"Updated: {file_status.file}")
self.fixed_count = fixed_count
- @staticmethod
- async def fix(file_status: FileStatus) -> bool:
+ async def fix(self, file_status: FileStatus) -> bool:
"""Fix a single file and write to disk.
Returns:
@@ -230,7 +247,35 @@ class Linter:
if file_status.notebook is None or file_status.contents is None:
return False
- generated_contents = Linter._generate_file_contents(file_status)
+ # Apply unsafe fixes if enabled
+ modified_notebook = file_status.notebook
+ if self.unsafe_fixes:
+ # Collect diagnostics by rule code
+ from collections import defaultdict
+
+ from marimo._lint.rules.base import UnsafeFixRule
+
+ diagnostics_by_rule = defaultdict(list)
+ for diagnostic in file_status.diagnostics:
+ if (
+ diagnostic.fixable == "unsafe"
+ and diagnostic.code in self.rule_lookup
+ ):
+ diagnostics_by_rule[diagnostic.code].append(diagnostic)
+
+ # Apply unsafe fixes once per rule
+ for rule_code, diagnostics in diagnostics_by_rule.items():
+ rule = self.rule_lookup[rule_code]
+ if isinstance(rule, UnsafeFixRule):
+ # Apply fix once per rule with all its diagnostics
+ modified_notebook = rule.apply_unsafe_fix(
+ modified_notebook, diagnostics
+ )
+
+ # Generate file contents from (possibly modified) notebook
+ generated_contents = Linter._generate_file_contents_from_notebook(
+ modified_notebook, file_status.file
+ )
# Only write if content changed
if file_status.contents != generated_contents:
diff --git a/marimo/_lint/rules/base.py b/marimo/_lint/rules/base.py
index b0b91379bf..b23037ba5a 100644
--- a/marimo/_lint/rules/base.py
+++ b/marimo/_lint/rules/base.py
@@ -2,12 +2,14 @@
from __future__ import annotations
from abc import ABC, abstractmethod
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Literal
from marimo._lint.diagnostic import Severity
if TYPE_CHECKING:
from marimo._lint.context import RuleContext
+ from marimo._lint.diagnostic import Diagnostic
+ from marimo._schemas.serialization import NotebookSerialization
class LintRule(ABC):
@@ -18,9 +20,28 @@ class LintRule(ABC):
name: str
description: str
severity: Severity
- fixable: bool
+ fixable: bool | Literal["unsafe"]
@abstractmethod
async def check(self, ctx: RuleContext) -> None:
"""Check notebook for violations of this rule using the provided context."""
pass
+
+
+class UnsafeFixRule(LintRule):
+ """Base class for rules that can apply unsafe fixes to notebook IR."""
+
+ @abstractmethod
+ def apply_unsafe_fix(
+ self, notebook: NotebookSerialization, diagnostics: list[Diagnostic]
+ ) -> NotebookSerialization:
+ """Apply unsafe fix to notebook IR.
+
+ Args:
+ notebook: The notebook to modify
+ diagnostics: List of diagnostics that triggered this fix
+
+ Returns:
+ Modified notebook serialization
+ """
+ pass
diff --git a/marimo/_lint/rules/formatting/__init__.py b/marimo/_lint/rules/formatting/__init__.py
index c5cb2477b0..0d618646b4 100644
--- a/marimo/_lint/rules/formatting/__init__.py
+++ b/marimo/_lint/rules/formatting/__init__.py
@@ -1,5 +1,6 @@
# Copyright 2025 Marimo. All rights reserved.
-from marimo._lint.rules.base import LintRule
+from marimo._lint.rules.base import LintRule, UnsafeFixRule
+from marimo._lint.rules.formatting.empty_cells import EmptyCellRule
from marimo._lint.rules.formatting.general import GeneralFormattingRule
from marimo._lint.rules.formatting.parsing import StderrRule, StdoutRule
@@ -7,6 +8,7 @@ FORMATTING_RULE_CODES: dict[str, type[LintRule]] = {
"MF001": GeneralFormattingRule,
"MF002": StdoutRule,
"MF003": StderrRule,
+ "MF004": EmptyCellRule,
}
__all__ = [
@@ -14,4 +16,6 @@ __all__ = [
"FORMATTING_RULE_CODES",
"StdoutRule",
"StderrRule",
+ "EmptyCellRule",
+ "UnsafeFixRule",
]
diff --git a/marimo/_lint/rules/formatting/empty_cells.py b/marimo/_lint/rules/formatting/empty_cells.py
new file mode 100644
index 0000000000..bc91c86c2c
--- /dev/null
+++ b/marimo/_lint/rules/formatting/empty_cells.py
@@ -0,0 +1,194 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+from typing import TYPE_CHECKING
+
+from marimo._ast.parse import ast_parse
+from marimo._lint.diagnostic import Diagnostic, Severity
+from marimo._lint.rules.base import UnsafeFixRule
+from marimo._schemas.serialization import NotebookSerialization
+from marimo._types.ids import CellId_t
+
+if TYPE_CHECKING:
+ from marimo._lint.context import RuleContext
+
+
+class EmptyCellRule(UnsafeFixRule):
+ """MF004: Empty cells that can be safely removed.
+
+ This rule identifies cells that contain only whitespace, comments, or `pass`
+ statements and can be safely removed from the notebook without affecting
+ functionality. Empty cells often accumulate during development and can
+ clutter the notebook structure.
+
+ ## What it does
+
+ Detects cells that contain only:
+ - Whitespace characters (spaces, tabs, newlines)
+ - Comments (lines starting with #)
+ - Pass statements (`pass`)
+ - Any combination of the above
+
+ ## Why is this bad?
+
+ Empty cells can:
+ - Create clutter in notebook structure
+ - Add unnecessary complexity to the execution graph
+ - Make notebooks harder to read and maintain
+ - Increase file size without adding value
+
+ While not functionally breaking, removing empty cells improves code
+ clarity and reduces visual noise.
+
+ ## Examples
+
+ **Problematic:**
+ ```python
+ # Cell 1: Only whitespace
+ ```
+
+ **Problematic:**
+ ```python
+ # Cell 2: Only comments
+ # This is just a comment
+ # Nothing else here
+ ```
+
+ **Problematic:**
+ ```python
+ # Cell 3: Only pass statement
+ pass
+ ```
+
+ **Problematic:**
+ ```python
+ # Cell 4: Mix of comments, whitespace, and pass
+ # Some comment
+
+ pass
+ # Another comment
+ ```
+
+ **Note:** This fix requires `--unsafe-fixes` because removing cells changes
+ the notebook structure, and potentially removes user-intended content.
+
+ ## References
+
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+ - [Best Practices](https://docs.marimo.io/guides/best_practices/)
+ """
+
+ code = "MF004"
+ name = "empty-cells"
+ description = "Empty cells that can be safely removed."
+ severity = Severity.FORMATTING
+ fixable = "unsafe"
+
+ async def check(self, ctx: RuleContext) -> None:
+ """Check for empty cells that can be removed."""
+ for i, cell in enumerate(ctx.notebook.cells):
+ if self._is_empty_cell(cell.code):
+ # Create diagnostic for this empty cell
+ idx = CellId_t(str(i))
+ diagnostic = Diagnostic(
+ message="Empty cell can be removed (contains only whitespace, comments, or pass)",
+ cell_id=[idx],
+ line=cell.lineno - 1, # Convert 1-based to 0-based
+ column=cell.col_offset,
+ fixable="unsafe",
+ )
+
+ await ctx.add_diagnostic(diagnostic)
+
+ def apply_unsafe_fix(
+ self, notebook: NotebookSerialization, diagnostics: list[Diagnostic]
+ ) -> NotebookSerialization:
+ """Remove empty cells from the notebook.
+
+ Args:
+ notebook: The notebook to modify
+ diagnostics: List of diagnostics containing cell information
+
+ Returns:
+ Modified notebook with empty cells removed
+ """
+ # Collect all cell IDs to remove from all diagnostics
+ cells_to_remove: set[CellId_t] = set()
+ for diagnostic in diagnostics:
+ if diagnostic.cell_id is not None:
+ (cell_id,) = diagnostic.cell_id
+ cells_to_remove.add(cell_id)
+
+ # Remove cells with matching IDs
+ cells = [
+ cell
+ for i, cell in enumerate(notebook.cells)
+ if CellId_t(str(i)) not in cells_to_remove
+ ]
+ return NotebookSerialization(
+ header=notebook.header,
+ version=notebook.version,
+ app=notebook.app,
+ cells=cells,
+ violations=notebook.violations,
+ valid=notebook.valid,
+ filename=notebook.filename,
+ )
+
+ def _is_empty_cell(self, code: str) -> bool:
+ """Check if a cell is considered empty.
+
+ Args:
+ code: The cell's source code
+
+ Returns:
+ True if the cell is empty (contains only whitespace, comments, or pass)
+ """
+ # Strip whitespace
+ stripped = code.strip()
+
+ # Empty after stripping whitespace
+ if not stripped:
+ return True
+
+ try:
+ # Parse the code to check what statements it contains
+ tree = ast_parse(stripped)
+
+ # If no statements, it's empty
+ if not tree.body:
+ return True
+
+ # Check if all statements are pass statements
+ for node in tree.body:
+ if not isinstance(node, ast.Pass):
+ return False
+
+ return True
+
+ except SyntaxError:
+ # If it doesn't parse, check if it's only comments
+ return self._is_only_comments(code)
+
+ def _is_only_comments(self, code: str) -> bool:
+ """Check if code contains only comments and whitespace.
+
+ Args:
+ code: The source code to check
+
+ Returns:
+ True if the code contains only comments and whitespace
+ """
+ lines = code.splitlines()
+
+ for line in lines:
+ stripped_line = line.strip()
+ # Skip empty lines
+ if not stripped_line:
+ continue
+ # If line doesn't start with #, it's not just a comment
+ if not stripped_line.startswith("#"):
+ return False
+
+ return True
diff --git a/mkdocs.yml b/mkdocs.yml
index 32594216f3..f14b1a50fb 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -100,10 +100,11 @@ nav:
- Multiple definitions: guides/lint_rules/rules/multiple_definitions.md
- Cycle dependencies: guides/lint_rules/rules/cycle_dependencies.md
- Setup cell dependencies: guides/lint_rules/rules/setup_cell_dependencies.md
- - Syntax Error: guides/lint_rules/rules/invalid_syntax.md
+ - Syntax error: guides/lint_rules/rules/invalid_syntax.md
- General formatting: guides/lint_rules/rules/general_formatting.md
- Parse stdout: guides/lint_rules/rules/parse_stdout.md
- Parse stderr: guides/lint_rules/rules/parse_stderr.md
+ - Empty cells: guides/lint_rules/rules/empty_cells.md
- SQL, dataframes, and plots:
- SQL, dataframes, and plots: guides/working_with_data/index.md
- DataFrames: guides/working_with_data/dataframes.md
diff --git a/scripts/generate_lint_docs.py b/scripts/generate_lint_docs.py
index c5d49ca19d..000d3450fe 100644
--- a/scripts/generate_lint_docs.py
+++ b/scripts/generate_lint_docs.py
@@ -42,7 +42,7 @@ class RuleInfo:
name: str
description: str
severity: Severity
- fixable: bool
+ fixable: bool | str
docstring: str
file_path: Path
class_name: str
@@ -61,7 +61,9 @@ def extract_rule_info_from_file(file_path: Path) -> list[RuleInfo]:
for node in ast.walk(tree):
if (isinstance(node, ast.ClassDef) and
- any(isinstance(base, ast.Name) and base.id in ["LintRule", "GraphRule"] for base in node.bases)):
+ any(isinstance(base, ast.Name) and base.id in ["LintRule",
+ "GraphRule",
+ "UnsafeFixRule"] for base in node.bases)):
# Extract class attributes
rule_data = {}
@@ -197,8 +199,8 @@ def validate_rule_info(rule: RuleInfo) -> list[str]:
if not isinstance(rule.severity, Severity):
issues.append(f"Invalid severity: {rule.severity}")
- if not isinstance(rule.fixable, bool):
- issues.append(f"Fixable must be a boolean, got {type(rule.fixable)}")
+ if not isinstance(rule.fixable, (bool, str)) or (isinstance(rule.fixable, str) and rule.fixable != "unsafe"):
+ issues.append(f"Fixable must be a boolean or 'unsafe', got {rule.fixable}")
# Validate docstring exists and is properly formatted
if not rule.docstring:
@@ -320,7 +322,12 @@ marimo's lint rules are organized into three main categories based on their seve
content += "|------|------|-------------|----------|\n"
for rule in sorted(rules, key=lambda r: r['code']):
- fixable_icon = "🛠️" if rule['fixable'] else "❌"
+ if rule['fixable'] is True:
+ fixable_icon = "🛠️"
+ elif rule['fixable'] == "unsafe":
+ fixable_icon = "⚠️"
+ else:
+ fixable_icon = "❌"
filename = rule['name'].replace("-", "_") + ".md"
rule_link = f"[{rule['code']}](rules/{filename})"
content += f"| {rule_link} | {rule['name']} | {rule['description']} | {fixable_icon} |\n"
@@ -330,6 +337,7 @@ marimo's lint rules are organized into three main categories based on their seve
content += """## Legend
- 🛠️ = Automatically fixable with `marimo check --fix`
+- ⚠️ = Fixable with `marimo check --fix --unsafe-fixes` (may change code behavior)
- ❌ = Not automatically fixable
## Configuration
@@ -350,9 +358,17 @@ def generate_rule_page(rule_details: dict[str, Any]) -> str:
rule = rule_details
icon, severity_name, _ = get_severity_info(rule['severity'])
+ # Determine fixable status
+ if rule['fixable'] is True:
+ fixable_status = '🛠️ Fixable'
+ elif rule['fixable'] == "unsafe":
+ fixable_status = '⚠️ Unsafe Fixable'
+ else:
+ fixable_status = '❌ Not Fixable'
+
content = f"""# {rule['code']}: {rule['name']}
-{icon} **{severity_name}** {'🛠️ Fixable' if rule['fixable'] else '❌ Not Fixable'}
+{icon} **{severity_name}** {fixable_status}
"""
diff --git a/tests/_lint/snapshots/empty_cells.txt b/tests/_lint/snapshots/empty_cells.txt
new file mode 100644
index 0000000000..7deb70e5cc
--- /dev/null
+++ b/tests/_lint/snapshots/empty_cells.txt
@@ -0,0 +1,30 @@
+warning[empty-cells]: Empty cell can be removed (contains only whitespace, comments, or pass)
+ --> tests/_lint/test_files/empty_cells.py:8:0
+ 8 | def _():
+ 9 | return
+ | ^
+ 10 |
+warning[empty-cells]: Empty cell can be removed (contains only whitespace, comments, or pass)
+ --> tests/_lint/test_files/empty_cells.py:12:0
+ 12 | @app.cell
+ 13 | def has_pass():
+ | ^
+ 14 | # This is just a comment
+warning[empty-cells]: Empty cell can be removed (contains only whitespace, comments, or pass)
+ --> tests/_lint/test_files/empty_cells.py:19:0
+ 19 | @app.cell
+ 20 | def has_comment():
+ | ^
+ 21 | # Only comment
+warning[empty-cells]: Empty cell can be removed (contains only whitespace, comments, or pass)
+ --> tests/_lint/test_files/empty_cells.py:26:0
+ 26 | @app.cell
+ 27 | def has_mix():
+ | ^
+ 28 |
+warning[empty-cells]: Empty cell can be removed (contains only whitespace, comments, or pass)
+ --> tests/_lint/test_files/empty_cells.py:34:0
+ 34 | @app.cell
+ 35 | def _empty_cell_with_just_whitespace():
+ | ^
+ 36 |
\ No newline at end of file
diff --git a/tests/_lint/snapshots/formatting.txt b/tests/_lint/snapshots/formatting.txt
index df51a1d962..2368df0c76 100644
--- a/tests/_lint/snapshots/formatting.txt
+++ b/tests/_lint/snapshots/formatting.txt
@@ -24,4 +24,10 @@ warning[general-formatting]: Unexpected statement, expected cell definitions.
11 |
warning[general-formatting]: Expected run guard statement
--> tests/_lint/test_files/formatting.py
- 1 | """Example to test formatting issues."""
\ No newline at end of file
+ 1 | """Example to test formatting issues."""
+warning[empty-cells]: Empty cell can be removed (contains only whitespace, comments, or pass)
+ --> tests/_lint/test_files/formatting.py:13:0
+ 13 | @app.cell
+ 14 | def _():
+ | ^
+ 15 | pass
\ No newline at end of file
diff --git a/tests/_lint/test_empty_cells.py b/tests/_lint/test_empty_cells.py
new file mode 100644
index 0000000000..685df66de4
--- /dev/null
+++ b/tests/_lint/test_empty_cells.py
@@ -0,0 +1,25 @@
+# Copyright 2025 Marimo. All rights reserved.
+"""Snapshot tests for empty cells lint rule."""
+
+from marimo._ast.parse import parse_notebook
+from tests._lint.utils import lint_notebook
+from tests.mocks import snapshotter
+
+snapshot = snapshotter(__file__)
+
+
+def test_empty_cells_detection_snapshot():
+ """Test snapshot for empty cells detection."""
+ file = "tests/_lint/test_files/empty_cells.py"
+ with open(file) as f:
+ code = f.read()
+
+ notebook = parse_notebook(code, filepath=file)
+ errors = lint_notebook(notebook)
+
+ # Format errors for snapshot
+ error_output = []
+ for error in errors:
+ error_output.append(error.format())
+
+ snapshot("empty_cells.txt", "\n".join(error_output))
diff --git a/tests/_lint/test_files/empty_cells.py b/tests/_lint/test_files/empty_cells.py
new file mode 100644
index 0000000000..58c5bda16c
--- /dev/null
+++ b/tests/_lint/test_files/empty_cells.py
@@ -0,0 +1,50 @@
+import marimo
+
+__generated_with = "0.15.5"
+app = marimo.App()
+
+
+def _():
+ return
+
+
+def has_pass():
+ # This is just a comment
+ pass
+ return
+
+
+def has_comment():
+ # Only comment
+ # Another comment
+ return
+
+
+def has_mix():
+
+ # Only whitespace and comment
+ pass
+ return
+
+
+def _empty_cell_with_just_whitespace():
+
+
+
+
+ return
+
+
+def normal_cell():
+ x = 1
+ return x,
+
+
+if __name__ == "__main__":
+ app.run()
\ No newline at end of file
diff --git a/tests/_lint/test_run_check.py b/tests/_lint/test_run_check.py
index 7c08e9dcf1..81d36552cd 100644
--- a/tests/_lint/test_run_check.py
+++ b/tests/_lint/test_run_check.py
@@ -181,7 +181,8 @@ class TestFileStatus:
)
# Since no notebook, fix should return False (no changes)
- result = await Linter.fix(status)
+ linter = Linter()
+ result = await linter.fix(status)
assert result is False
# File should remain unchanged
@@ -214,7 +215,8 @@ class TestFileStatus:
)
# Since no notebook, fix should return False (no changes)
- result = await Linter.fix(status)
+ linter = Linter()
+ result = await linter.fix(status)
assert result is False
# File should remain unchanged
@@ -269,7 +271,8 @@ class TestFileStatus:
)
# Since no notebook, fix should return False (no changes)
- result = await Linter.fix(status)
+ linter = Linter()
+ result = await linter.fix(status)
assert result is False
# File should remain unchanged
@@ -340,10 +343,11 @@ def __():
# Test fixing (if notebook is available)
if file_status.notebook is not None:
- # Use Linter.fix() static method
+ # Use Linter.fix() method
import asyncio
- result = asyncio.run(Linter.fix(file_status))
+ linter = Linter()
+ result = asyncio.run(linter.fix(file_status))
assert isinstance(result, bool)
def test_error_handling_in_run_check(self):