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
feat: Lint rule to detect ordering discrepancies on top level functions (#8996)
Dylan Madisettib713f69a214f
diff --git a/docs/guides/lint_rules/index.md b/docs/guides/lint_rules/index.mdindex 8b7febcde3..5523db2411 100644--- a/docs/guides/lint_rules/index.md+++ b/docs/guides/lint_rules/index.md@@ -1,8 +1,9 @@# Lint Rules-marimo includes a linter that helps you write better notebooks. The linter-checks for various issues that could prevent your notebook from running-correctly or cause confusion.+<!-- Autogenerated! Please edit scripts/generate_lint_docs.py instead --!>++marimo includes a linter that helps you write better notebooks. The linter checks for various issues that could prevent your notebook from running correctly or cause confusion.+## Usage@@ -43,6 +44,7 @@ These issues may cause runtime problems.|------|------|-------------|----------|| [MR001](rules/self_import.md) | self-import | Importing a module with the same name as the file | ❌ || [MR002](rules/branch_expression.md) | branch-expression | Branch statements with output expressions that won't be displayed | ❌ |+| [MR003](rules/reusable_definition_order.md) | reusable-definition-order | Reusable definitions depending on later reusable definitions | ⚠️ |### ✨ Formatting Rulesdiff --git a/docs/guides/lint_rules/rules/markdown_dedent.md b/docs/guides/lint_rules/rules/markdown_dedent.mddeleted file mode 100644index e0e3aa0c79..0000000000--- a/docs/guides/lint_rules/rules/markdown_dedent.md+++ /dev/null@@ -1,50 +0,0 @@-# MF007: markdown-indentation--✨ **Formatting** 🛠️ Fixable--MF007: Markdown strings in `mo.md()` should be dedented.--## What it does--Checks cells containing `mo.md()` calls to see if the markdown string-content has unnecessary leading whitespace that should be removed.--## Why is this bad?--Indented markdown strings:--- Are harder to read when viewing the source code-- Produce larger diffs when making changes-- Don't match the standard marimo formatting style-- Can be confusing when the indentation doesn't reflect the markdown structure--## Examples--**Problematic:**--```python-mo.md(- r"""- # Title-- Some content here.- """-)-```--**Solution:**--```python-mo.md(r"""-# Title--Some content here.-""")-```--**Note:** This fix is automatically applied with `marimo check --fix`.--## References--- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)-- [Best Practices](https://docs.marimo.io/guides/best_practices/)diff --git a/docs/guides/lint_rules/rules/reusable_definition_order.md b/docs/guides/lint_rules/rules/reusable_definition_order.mdnew file mode 100644index 0000000000..a088f9e916--- /dev/null+++ b/docs/guides/lint_rules/rules/reusable_definition_order.md@@ -0,0 +1,91 @@+# MR003: reusable-definition-order++⚠️ **Runtime** ⚠️ Unsafe Fixable++MR003: Invalid ordering of potentially reusable definitions.++## What it does++marimo serializes reusable definitions in notebook order. Like all python+scripts, a reusable function cannot refer to a variable that has _not yet+been defined_. While ordering in marimo normally doesn't matter, for reuse+as a module or script, dependent top level definitions must be ordered+correctly.++This rule flags and fixes function or class definitions that would normally+be saved as "reusable", but cannot due to cell ordering.++## Why is this bad?++When a reusable definition depends on another reusable definition declared+later in the notebook:++- the definition cannot be serialized as reusable+- imports from other notebooks or Python modules may fail++## Examples++**Problematic:**+```python+def uses_offset(x: int = offset()) -> int:+ # This will run in marimo, but will cause an error if run as a script!+ # `offset` is not defined!+ return x + 1+++def offset() -> int:+ return 1+```++**Problematic:**+```python+def _():+ # This could be reusable if it was defined after `decorate`.+ class Wrapped:+ @decorate+ def value(self) -> int:+ return 1+++def decorate(fn):+ return fn+```++## References++- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)+- [setup](https://docs.marimo.io/guides/understanding_errors/setup/)+- [Reusing functions](https://docs.marimo.io/guides/reusing_functions/)++## Solution++Move the referenced reusable definitions earlier in the notebook so they+appear before the reusable definition that depends on them.++```python+def offset() -> int:+ return 1+++def uses_offset(x: int = offset()) -> int:+ return x + 1+```++## Unsafe fix++This rule can be fixed with:++```bash+marimo check --fix --unsafe-fixes my_notebook.py+```++The unsafe fix reorders the provider cells earlier in the notebook. This+is marked unsafe because changing cell order changes the document+structure, even when the resulting notebook is still valid.+diff --git a/marimo/_lint/rules/runtime/__init__.py b/marimo/_lint/rules/runtime/__init__.pyindex 1aa36beef4..b024f566cb 100644--- a/marimo/_lint/rules/runtime/__init__.py+++ b/marimo/_lint/rules/runtime/__init__.py@@ -3,15 +3,20 @@ from __future__ import annotationsfrom marimo._lint.rules.base import LintRulefrom marimo._lint.rules.runtime.branch_expression import BranchExpressionRule+from marimo._lint.rules.runtime.reusable_definition_order import (+ ReusableDefinitionOrderRule,+)from marimo._lint.rules.runtime.self_import import SelfImportRuleRUNTIME_RULE_CODES: dict[str, type[LintRule]] = {"MR001": SelfImportRule,"MR002": BranchExpressionRule,+ "MR003": ReusableDefinitionOrderRule,}__all__ = ["BranchExpressionRule",+ "ReusableDefinitionOrderRule","SelfImportRule","RUNTIME_RULE_CODES",]diff --git a/marimo/_lint/rules/runtime/reusable_definition_order.py b/marimo/_lint/rules/runtime/reusable_definition_order.pynew file mode 100644index 0000000000..7d2accd2fe--- /dev/null+++ b/marimo/_lint/rules/runtime/reusable_definition_order.py@@ -0,0 +1,330 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import ast+from dataclasses import replace+from pathlib import Path+from typing import TYPE_CHECKING++from marimo._ast.compiler import compile_cell+from marimo._ast.names import SETUP_CELL_NAME+from marimo._ast.parse import ast_parse+from marimo._ast.toplevel import HINT_ORDER_DEPENDENT, TopLevelExtraction+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++_HINT_ORDER_DEPENDENT_PREFIX = HINT_ORDER_DEPENDENT.split("{}")[0]++if TYPE_CHECKING:+ from marimo._ast.cell import CellImpl+ from marimo._ast.toplevel import TopLevelStatus+ from marimo._lint.context import RuleContext+ from marimo._schemas.serialization import CellDef+++class ReusableDefinitionOrderRule(UnsafeFixRule):+ """MR003: Invalid ordering of potentially reusable definitions.++ This rule detects cells that could be reusable definitions (i.e., decorated+ with ``@app.function`` or ``@app.class_definition``) but which _cannot_ be+ safely serialized as reusable due to the ordering of marimo cells.+++ ## What it does++ marimo serializes reusable definitions in notebook order. Like all python+ scripts, a reusable function cannot refer to a variable that has _not yet+ been defined_. While ordering in marimo normally doesn't matter, for reuse+ as a module or script, dependent top level definitions must be ordered+ correctly.++ This rule flags and fixes function or class definitions that would normally+ be saved as "reusable", but cannot due to cell ordering.++ ## Why is this bad?++ When a reusable definition depends on another reusable definition declared+ later in the notebook:++ - the definition cannot be serialized as reusable+ - imports from other notebooks or Python modules may fail+++ ## Examples++ **Problematic:**+ ```python+ @app.function+ def uses_offset(x: int = offset()) -> int:+ # This will run in marimo, but will cause an error if run as a script!+ # `offset` is not defined!+ return x + 1+++ @app.function+ def offset() -> int:+ return 1+ ```++ **Problematic:**+ ```python+ @app.cell+ def _():+ # This could be reusable if it was defined after `decorate`.+ class Wrapped:+ @decorate+ def value(self) -> int:+ return 1+++ @app.function+ def decorate(fn):+ return fn+ ```++ ## Solution++ Move the referenced reusable definitions earlier in the notebook so they+ appear before the reusable definition that depends on them.++ ```python+ @app.function+ def offset() -> int:+ return 1+++ @app.function+ def uses_offset(x: int = offset()) -> int:+ return x + 1+ ```++ ## Unsafe fix++ This rule can be fixed with:++ ```bash+ marimo check --fix --unsafe-fixes my_notebook.py+ ```++ The unsafe fix reorders the provider cells earlier in the notebook. This+ is marked unsafe because changing cell order changes the document+ structure, even when the resulting notebook is still valid.+++ ## References++ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)+ - [setup](https://docs.marimo.io/guides/understanding_errors/setup/)+ - [Reusing functions](https://docs.marimo.io/guides/reusing_functions/)+ """++ code = "MR003"+ name = "reusable-definition-order"+ description = (+ "Reusable definitions depending on later reusable definitions"+ )+ severity = Severity.RUNTIME+ fixable = "unsafe"++ async def check(self, ctx: RuleContext) -> None:+ extraction, notebook_indices = self._extract_notebook(ctx.notebook)++ for status, notebook_index in zip(+ extraction.statuses, notebook_indices+ ):+ if not (+ status.hint+ and status.hint.startswith(_HINT_ORDER_DEPENDENT_PREFIX)+ ):+ continue++ notebook_cell = ctx.notebook.cells[notebook_index]+ definition_name = self._get_definition_name(status)+ line, column = self._get_definition_line_info(+ notebook_cell, definition_name+ )+ refs = ", ".join(+ f"`{name}`" for name in sorted(status.dependencies)+ )+ diagnostic = Diagnostic(+ message=(+ f"Reusable definition '{definition_name}' depends on reusable "+ f"definition(s) declared later in the notebook: {refs}"+ ),+ cell_id=[CellId_t(str(notebook_index))],+ line=line,+ column=column,+ fixable="unsafe",+ fix=(+ "Move the referenced reusable definition(s) earlier in the "+ f"notebook, before `{definition_name}`."+ ),+ )+ await ctx.add_diagnostic(diagnostic)++ def apply_unsafe_fix(+ self, notebook: NotebookSerialization, diagnostics: list[Diagnostic]+ ) -> NotebookSerialization:+ del diagnostics++ cells = list(notebook.cells)+ extraction, notebook_indices = self._extract_notebook(notebook)+ provider_order = self._stable_provider_order(+ extraction, notebook_indices+ )+ if provider_order is None:+ return replace(notebook, cells=cells)++ sorted_provider_positions = sorted(provider_order)+ reordered_provider_cells = [cells[index] for index in provider_order]+ for provider_position, cell in zip(+ sorted_provider_positions, reordered_provider_cells+ ):+ cells[provider_position] = cell++ return replace(notebook, cells=cells)++ def _stable_provider_order(+ self, extraction: TopLevelExtraction, notebook_indices: list[int]+ ) -> list[int] | None:+ provider_indices = {+ self._get_definition_name(status): notebook_index+ for status, notebook_index in zip(+ extraction.statuses, notebook_indices+ )+ if status.is_toplevel+ or (+ status.hint+ and status.hint.startswith(_HINT_ORDER_DEPENDENT_PREFIX)+ )+ }+ if not provider_indices:+ return []++ graph: dict[int, set[int]] = {+ notebook_index: set()+ for notebook_index in provider_indices.values()+ }+ indegree = {notebook_index: 0 for notebook_index in graph}++ for status, notebook_index in zip(+ extraction.statuses, notebook_indices+ ):+ if not (+ status.is_toplevel+ or (+ status.hint+ and status.hint.startswith(_HINT_ORDER_DEPENDENT_PREFIX)+ )+ ):+ continue+ for dependency_name in status.dependencies:+ dependency_index = provider_indices.get(dependency_name)+ if (+ dependency_index is None+ or dependency_index == notebook_index+ or notebook_index in graph[dependency_index]+ ):+ continue+ graph[dependency_index].add(notebook_index)+ indegree[notebook_index] += 1++ ready = sorted(+ notebook_index+ for notebook_index, degree in indegree.items()+ if degree == 0+ )+ ordered: list[int] = []+ while ready:+ notebook_index = ready.pop(0)+ ordered.append(notebook_index)+ for dependent_index in sorted(graph[notebook_index]):+ indegree[dependent_index] -= 1+ if indegree[dependent_index] == 0:+ ready.append(dependent_index)+ ready.sort()++ if len(ordered) != len(graph):+ return None+ return ordered++ @staticmethod+ def _move_cells_before(+ cells: list[CellDef], source_indices: list[int], target_index: int+ ) -> list[CellDef]:+ to_move = set(source_indices)+ moved_cells = [cell for i, cell in enumerate(cells) if i in to_move]+ remaining_cells = [+ cell for i, cell in enumerate(cells) if i not in to_move+ ]+ return (+ remaining_cells[:target_index]+ + moved_cells+ + remaining_cells[target_index:]+ )++ @staticmethod+ def _extract_notebook(+ notebook: NotebookSerialization,+ ) -> tuple[TopLevelExtraction, list[int]]:+ from marimo._ast.cell import CellConfig++ compiled_cells: list[CellImpl] = []+ notebook_indices: list[int] = []+ setup_cell: CellImpl | None = None+ filename = (+ notebook.filename+ if notebook.filename and Path(notebook.filename).exists()+ else None+ )++ for index, cell in enumerate(notebook.cells):+ try:+ compiled = compile_cell(+ cell.code,+ cell_id=CellId_t(str(index)),+ filename=filename,+ ).configure(CellConfig.from_dict(cell.options))+ except SyntaxError:+ continue++ if cell.name == SETUP_CELL_NAME:+ setup_cell = compiled+ else:+ compiled_cells.append(compiled)+ notebook_indices.append(index)++ return TopLevelExtraction.from_cells(+ compiled_cells, setup=setup_cell+ ), notebook_indices++ @staticmethod+ def _get_definition_line_info(+ cell: CellDef, definition_name: str+ ) -> tuple[int, int]:+ try:+ tree = ast_parse(cell.code)+ except SyntaxError:+ return cell.lineno, cell.col_offset + 1++ for node in tree.body:+ if (+ isinstance(+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ )+ and node.name == definition_name+ ):+ return (+ cell.lineno + node.lineno - 1,+ cell.col_offset + node.col_offset + 1,+ )++ return cell.lineno, cell.col_offset + 1++ @staticmethod+ def _get_definition_name(status: TopLevelStatus) -> str:+ if status.defs:+ return sorted(status.defs)[0]+ return status.namediff --git a/mkdocs.yml b/mkdocs.ymlindex 6fe0f86da1..0cb04f6517 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -205,10 +205,10 @@ nav:- 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- - Markdown Dedent: guides/lint_rules/rules/markdown_dedent.md- - Markdown Indentation: guides/lint_rules/rules/markdown_indentation.md+ - Markdown indentation: guides/lint_rules/rules/markdown_indentation.md- SQL parse error: guides/lint_rules/rules/sql_parse_error.md- Misc parse log: guides/lint_rules/rules/misc_log_capture.md+ - Reusable ordering: guides/lint_rules/rules/reusable_definition_order.md- Testing:- Testing notebooks: guides/testing/index.md- pytest: guides/testing/pytest.mddiff --git a/scripts/generate_lint_docs.py b/scripts/generate_lint_docs.pyold mode 100644new mode 100755index d5514ee125..ade09dba4d--- a/scripts/generate_lint_docs.py+++ b/scripts/generate_lint_docs.py@@ -1,3 +1,4 @@+#!/usr/bin/env python3# /// script# requires-python = ">=3.13,<3.14"# dependencies = []@@ -273,11 +274,14 @@ def generate_main_index_page(rules_by_severity: dict[Severity, list[dict[str, An"""Generate the main lint rules index page."""content = """# Lint Rules-marimo includes a comprehensive linting system that helps you write better, more reliable notebooks. The linter checks for various issues that could prevent your notebook from running correctly or cause confusion.+<!-- Autogenerated! Please edit scripts/generate_lint_docs.py instead --!>-## How to Use+marimo includes a linter that helps you write better notebooks. The linter checks for various issues that could prevent your notebook from running correctly or cause confusion.-You can run the linter using the CLI:++## Usage++Run the linter using the CLI:```bash# Check all notebooks in current directorydiff --git a/tests/_lint/snapshots/reusable_definition_order_errors.txt b/tests/_lint/snapshots/reusable_definition_order_errors.txtnew file mode 100644index 0000000000..ff9dad54d0--- /dev/null+++ b/tests/_lint/snapshots/reusable_definition_order_errors.txt@@ -0,0 +1,7 @@+error[reusable-definition-order]: Reusable definition 'uses_offset' depends on reusable definition(s) declared later in the notebook: `offset`+ --> tests/_lint/test_files/reusable_definition_order.py:7:1+ 7 | @app.function+ 8 | def uses_offset(x: int = offset()) -> int:+ | ^+ 9 | return x + 1+hint: Move the referenced reusable definition(s) earlier in the notebook, before `uses_offset`.diff --git a/tests/_lint/test_files/reusable_definition_order.py b/tests/_lint/test_files/reusable_definition_order.pynew file mode 100644index 0000000000..28334291e4--- /dev/null+++ b/tests/_lint/test_files/reusable_definition_order.py@@ -0,0 +1,32 @@+import marimo++__generated_with = "0.18.0"+app = marimo.App()+++def uses_offset(x: int = offset()) -> int:+ return x + 1+++def _():+ scale = 2+ return (scale,)+++def _(scale):+ def local_only(x: int = scale) -> int:+ return x + 1++ return+++def offset() -> int:+ return 1+++if __name__ == "__main__":+ app.run()diff --git a/tests/_lint/test_reusable_definition_order.py b/tests/_lint/test_reusable_definition_order.pynew file mode 100644index 0000000000..044f1d9276--- /dev/null+++ b/tests/_lint/test_reusable_definition_order.py@@ -0,0 +1,170 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from marimo._ast.parse import parse_notebook+from marimo._lint.rules.runtime.reusable_definition_order import (+ ReusableDefinitionOrderRule,+)+from tests._lint.utils import lint_notebook+++def test_reusable_definition_order_unsafe_fix_reorders_provider_cells():+ code = """import marimo++__generated_with = "0.18.0"+app = marimo.App()+++def uses_offset(x: int = offset()) -> int:+ return x + 1+++def offset() -> int:+ return 1+++if __name__ == "__main__":+ app.run()+"""+ notebook = parse_notebook(code, filepath="test.py")+ diagnostics = lint_notebook(notebook)++ assert [diagnostic.code for diagnostic in diagnostics] == ["MR003"]++ fixed = ReusableDefinitionOrderRule().apply_unsafe_fix(+ notebook, diagnostics+ )++ assert fixed.cells[0].name == "offset"+ assert fixed.cells[1].name == "uses_offset"+ assert not [+ diagnostic+ for diagnostic in lint_notebook(fixed)+ if diagnostic.code == "MR003"+ ]+++def test_reusable_definition_order_unsafe_fix_preserves_provider_order():+ code = """import marimo++__generated_with = "0.18.0"+app = marimo.App()+++def uses_both(+ one: int = first(),+ two: int = second(),+) -> tuple[int, int]:+ return one, two+++def first() -> int:+ return 1+++def second() -> int:+ return 2+++if __name__ == "__main__":+ app.run()+"""+ notebook = parse_notebook(code, filepath="test.py")+ diagnostics = lint_notebook(notebook)++ assert [diagnostic.code for diagnostic in diagnostics] == ["MR003"]++ fixed = ReusableDefinitionOrderRule().apply_unsafe_fix(+ notebook, diagnostics+ )++ assert [cell.name for cell in fixed.cells[:3]] == [+ "first",+ "second",+ "uses_both",+ ]+ assert not [+ diagnostic+ for diagnostic in lint_notebook(fixed)+ if diagnostic.code == "MR003"+ ]+++def test_reusable_definition_order_unsafe_fix_chained_dependencies():+ code = """import marimo++__generated_with = "0.18.0"+app = marimo.App()+++def a(x: int = b()) -> int:+ return x+++def b(x: int = c()) -> int:+ return x+++def c() -> int:+ return 1+++if __name__ == "__main__":+ app.run()+"""+ notebook = parse_notebook(code, filepath="test.py")+ diagnostics = lint_notebook(notebook)++ assert {d.code for d in diagnostics} == {"MR003"}++ fixed = ReusableDefinitionOrderRule().apply_unsafe_fix(+ notebook, diagnostics+ )++ assert [cell.name for cell in fixed.cells[:3]] == ["c", "b", "a"]+ assert not [+ diagnostic+ for diagnostic in lint_notebook(fixed)+ if diagnostic.code == "MR003"+ ]+++def test_reusable_definition_order_unsafe_fix_does_not_move_for_setup():+ code = """import marimo++__generated_with = "0.18.0"+app = marimo.App()+++with app.setup:+ def uses_offset(x: int = offset()) -> int:+ return x + 1+++def offset() -> int:+ return 1+++if __name__ == "__main__":+ app.run()+"""+ notebook = parse_notebook(code, filepath="test.py")+ original_order = [cell.name for cell in notebook.cells]+ diagnostics = lint_notebook(notebook)++ assert not [d for d in diagnostics if d.code == "MR003"]++ fixed = ReusableDefinitionOrderRule().apply_unsafe_fix(+ notebook, diagnostics+ )++ assert [cell.name for cell in fixed.cells] == original_orderdiff --git a/tests/_lint/test_rule_selector.py b/tests/_lint/test_rule_selector.pyindex 5db60cc660..4338ae5575 100644--- a/tests/_lint/test_rule_selector.py+++ b/tests/_lint/test_rule_selector.py@@ -26,7 +26,7 @@ class TestResolveRules:rules = resolve_rules({"select": ["MB", "MR"]})codes = {r.code for r in rules}assert all(c.startswith(("MB", "MR")) for c in codes)- assert len(rules) == 7 # 5 MB + 2 MR+ assert len(rules) == 8 # 5 MB + 3 MRdef test_select_all(self):rules = resolve_rules({"select": ["ALL"]})diff --git a/tests/_lint/test_snapshot.py b/tests/_lint/test_snapshot.pyindex 540355718e..c078b1e45f 100644--- a/tests/_lint/test_snapshot.py+++ b/tests/_lint/test_snapshot.py@@ -258,3 +258,19 @@ def test_branch_expression_snapshot():error_output.append(error.format())snapshot("branch_expression_errors.txt", "\n".join(error_output))+++def test_reusable_definition_order_snapshot():+ """Test snapshot for reusable definition ordering error."""+ file = "tests/_lint/test_files/reusable_definition_order.py"+ with open(file) as f:+ code = f.read()++ notebook = parse_notebook(code, filepath=file)+ errors = lint_notebook(notebook)++ error_output = []+ for error in errors:+ error_output.append(error.format())++ snapshot("reusable_definition_order_errors.txt", "\n".join(error_output))