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
lint rule: check for branching expressions (#7287)
Dylan Madisettiad5ff771072e
diff --git a/docs/guides/lint_rules/index.md b/docs/guides/lint_rules/index.mdindex 60d7288280..1cfa916e88 100644--- a/docs/guides/lint_rules/index.md+++ b/docs/guides/lint_rules/index.md@@ -40,6 +40,7 @@ These issues may cause runtime problems.| Code | Name | Description | Fixable ||------|------|-------------|----------|| [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 | ❌ |### ✨ Formatting Rules@@ -53,7 +54,7 @@ These are style and formatting issues.| [MF004](rules/empty_cells.md) | empty-cells | Empty cells that can be safely removed. | ⚠️ || [MF005](rules/sql_parse_error.md) | sql-parse-error | SQL parsing errors during dependency analysis | ❌ || [MF006](rules/misc_log_capture.md) | misc-log-capture | Miscellaneous log messages during processing | ❌ |-| [MF007](rules/markdown_indentation.md) | markdown-indentation | Markdown cells in `mo.md()` should be dedented. | 🛠️ |+| [MF007](rules/markdown_indentation.md) | markdown-indentation | Markdown cells in `mo.md()` should be properly indented. | 🛠️ |## Legenddiff --git a/docs/guides/lint_rules/rules/branch_expression.md b/docs/guides/lint_rules/rules/branch_expression.mdnew file mode 100644index 0000000000..9594c64cb3--- /dev/null+++ b/docs/guides/lint_rules/rules/branch_expression.md@@ -0,0 +1,74 @@+# MR002: branch-expression++⚠️ **Runtime** ❌ Not Fixable++MR002: Branch statements with output expressions that won't be displayed.++## Why is this bad?++When output expressions are nested inside branches at the end of a cell:+- The expressions execute but produce no visible output+- Users expect to see the result (like mo.md(), string literals, etc.)+- This can lead to confusion about whether code is running correctly+- It violates the principle of least surprise++This is a runtime issue because it causes unexpected behavior where the user's+intended output is silently ignored.++## Examples++**Problematic:**+```python+if condition:+ mo.md("Result A") # Won't be displayed+else:+ mo.md("Result B") # Won't be displayed+```++**Problematic:**+```python+match value:+ case 1:+ "Too short" # Won't be displayed+ case _:+ value # Won't be displayed+```++**Not flagged:**+```python+if condition:+ print("Debug message") # Function calls+```++**Solution:**+```python+# Assign to a variable that marimo will display+result = mo.md("Result A") if condition else mo.md("Result B")+result+```++**Solution:**+```python+# Create a default variable for response.+result = None+if condition:+ result = expr+else:+ result = other+result+```++**Alternative Solution (if no output intended):**+```python+# Use a dummy variable to indicate intentional suppression+if condition:+ _ = expr+else:+ _ = other+```++## References++- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)+- [Reactivity](https://docs.marimo.io/guides/reactivity/)+diff --git a/examples/ai/chat/streaming_openai.py b/examples/ai/chat/streaming_openai.pyindex 58b600e8a6..c3df1749c6 100644--- a/examples/ai/chat/streaming_openai.py+++ b/examples/ai/chat/streaming_openai.py@@ -95,16 +95,14 @@ def _(mo):@app.celldef _(chatbot, mo):# Show chat history- if hasattr(chatbot, "value"):- mo.md(f"**Chat history:** {len(chatbot.value)} messages")+ mo.md(f"**Chat history:** {len(chatbot.value)} messages") if hasattr(chatbot, "value") else Nonereturn@app.celldef _(chatbot):# Display full history- if hasattr(chatbot, "value"):- chatbot.value+ chatbot.value if hasattr(chatbot, "value") else Nonereturndiff --git a/examples/outputs/conditional_output.py b/examples/outputs/conditional_output.pyindex adda40c421..118343cefc 100644--- a/examples/outputs/conditional_output.py+++ b/examples/outputs/conditional_output.py@@ -34,18 +34,18 @@ def _(checkbox):@app.cell(hide_code=True)def _(mo):mo.md("""- The next cell does **not** show anything, since an if statement does not- have a value:- """)- return-+ The following cell would **not** show anything, since an if statement does+ not have a value:-def _(checkbox, mo):+ ```python+ # Intentionally demonstrates that if statements don't display expressions+ # Using _ to suppress the lint warning while keeping the exampleif checkbox.value:mo.md("Checkbox is checked")else:mo.md("Checkbox is not checked")+ ```+ """)returndiff --git a/examples/sql/misc/database_explorer.py b/examples/sql/misc/database_explorer.pyindex 929a559ee6..5f6294382c 100644--- a/examples/sql/misc/database_explorer.py+++ b/examples/sql/misc/database_explorer.py@@ -50,7 +50,7 @@ def _(mo, os):@app.celldef _(database_url, duckdb):if database_url.value:- duckdb.sql(+ _ = duckdb.sql(f"""INSTALL postgres;LOAD postgres;diff --git a/marimo/_lint/rules/runtime/__init__.py b/marimo/_lint/rules/runtime/__init__.pyindex efa4ff76db..402d2df6cd 100644--- a/marimo/_lint/rules/runtime/__init__.py+++ b/marimo/_lint/rules/runtime/__init__.py@@ -2,13 +2,16 @@from __future__ import annotationsfrom marimo._lint.rules.base import LintRule+from marimo._lint.rules.runtime.branch_expression import BranchExpressionRulefrom marimo._lint.rules.runtime.self_import import SelfImportRuleRUNTIME_RULE_CODES: dict[str, type[LintRule]] = {"MR001": SelfImportRule,+ "MR002": BranchExpressionRule,}__all__ = [+ "BranchExpressionRule","SelfImportRule","RUNTIME_RULE_CODES",]diff --git a/marimo/_lint/rules/runtime/branch_expression.py b/marimo/_lint/rules/runtime/branch_expression.pynew file mode 100644index 0000000000..ce2a6e4a56--- /dev/null+++ b/marimo/_lint/rules/runtime/branch_expression.py@@ -0,0 +1,274 @@+# 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 LintRule++if TYPE_CHECKING:+ from marimo._lint.context import RuleContext+ from marimo._schemas.serialization import CellDef+++class BranchExpressionRule(LintRule):+ """MR002: Branch statements with output expressions that won't be displayed.++ This rule detects when the last statement in a cell is a branch (if/elif/else,+ match, or try/except/finally) containing expressions that produce output. In+ marimo, only the last expression at the top level of a cell is displayed.+ Expressions nested inside branches will execute but not be shown to the user,+ which can be confusing if the user expected to see output.++ ## Why is this bad?++ When output expressions are nested inside branches at the end of a cell:+ - The expressions execute but produce no visible output+ - Users expect to see the result (like mo.md(), string literals, etc.)+ - This can lead to confusion about whether code is running correctly+ - It violates the principle of least surprise++ This is a runtime issue because it causes unexpected behavior where the user's+ intended output is silently ignored.++ ## Examples++ **Problematic:**+ ```python+ if condition:+ mo.md("Result A") # Won't be displayed+ else:+ mo.md("Result B") # Won't be displayed+ ```++ **Problematic:**+ ```python+ match value:+ case 1:+ "Too short" # Won't be displayed+ case _:+ value # Won't be displayed+ ```++ **Not flagged:**+ ```python+ if condition:+ print("Debug message") # Function calls+ ```++ **Solution:**+ ```python+ # Assign to a variable that marimo will display+ result = mo.md("Result A") if condition else mo.md("Result B")+ result+ ```++ **Solution:**+ ```python+ # Create a default variable for response.+ result = None+ if condition:+ result = expr+ else:+ result = other+ result+ ```++ **Alternative Solution (if no output intended):**+ ```python+ # Use a dummy variable to indicate intentional suppression+ if condition:+ _ = expr+ else:+ _ = other+ ```++ ## References++ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)+ - [Reactivity](https://docs.marimo.io/guides/reactivity/)+ """++ code = "MR002"+ name = "branch-expression"+ description = (+ "Branch statements with output expressions that won't be displayed"+ )+ severity = Severity.RUNTIME+ fixable = False++ async def check(self, ctx: RuleContext) -> None:+ """Check for branch statements with trailing expressions."""+ for cell in ctx.notebook.cells:+ # Skip empty cells+ if not cell.code.strip():+ continue++ try:+ tree = ast_parse(cell.code)++ # Check if there are any statements+ if not tree.body:+ continue++ # Get the last statement+ last_stmt = tree.body[-1]++ # Check if it's a branch statement+ if isinstance(last_stmt, ast.If):+ await self._check_if_statement(last_stmt, cell, ctx)+ elif isinstance(last_stmt, ast.Match):+ await self._check_match_statement(last_stmt, cell, ctx)+ elif isinstance(last_stmt, ast.Try):+ await self._check_try_statement(last_stmt, cell, ctx)++ except SyntaxError:+ # Skip cells that don't parse+ continue++ async def _check_if_statement(+ self, node: ast.If, cell: CellDef, ctx: RuleContext+ ) -> None:+ """Check if an if statement has branches with output expressions."""+ branches = self._collect_if_branches(node)++ # Check if ANY branch has an output expression+ if not branches:+ return++ if any(self._has_output_expression(branch) for branch in branches):+ await self._report_diagnostic(node, cell, ctx, "if statement")++ async def _check_match_statement(+ self, node: ast.Match, cell: CellDef, ctx: RuleContext+ ) -> None:+ """Check if a match statement has cases with output expressions."""+ if not node.cases:+ return++ branches = [case.body for case in node.cases]++ # Check if ANY case has an output expression+ if any(self._has_output_expression(branch) for branch in branches):+ await self._report_diagnostic(node, cell, ctx, "match statement")++ async def _check_try_statement(+ self, node: ast.Try, cell: CellDef, ctx: RuleContext+ ) -> None:+ """Check if a try statement has branches with output expressions."""+ branches = [node.body]++ # Add exception handlers+ for handler in node.handlers:+ branches.append(handler.body)++ # Add else clause if present+ if node.orelse:+ branches.append(node.orelse)++ # Add finally clause if present+ if node.finalbody:+ branches.append(node.finalbody)++ # Check if ANY branch has an output expression+ if any(self._has_output_expression(branch) for branch in branches):+ await self._report_diagnostic(node, cell, ctx, "try statement")++ def _collect_if_branches(self, node: ast.If) -> list[list[ast.stmt]]:+ """Collect all branches from an if/elif/else statement."""+ branches = [node.body]++ # Process orelse (could be elif or else)+ current = node+ while current.orelse:+ if len(current.orelse) == 1 and isinstance(+ current.orelse[0], ast.If+ ):+ # This is an elif+ current = current.orelse[0]+ branches.append(current.body)+ else:+ # This is an else+ branches.append(current.orelse)+ break++ return branches++ def _has_output_expression(self, stmts: list[ast.stmt]) -> bool:+ """Check if a branch has a trailing value expression.++ Returns True for expressions that produce values:+ - Constants: 42, "string", True, None+ - Names: x, obj, slider+ - Attributes: obj.attr, slider.value+ - Operations: a + b, a == b, not x+ - Marimo output calls: mo.md(), mo.ui.button()++ Returns False for:+ - All function calls (assumed side effects): func(), obj.method()+ - Except marimo output calls which ARE flagged+ """+ if not stmts:+ return False++ last_stmt = stmts[-1]+ if not isinstance(last_stmt, ast.Expr):+ return False++ expr = last_stmt.value++ # For calls, only flag marimo output calls+ if isinstance(expr, ast.Call):+ func = expr.func++ # Marimo output calls should be flagged (mo.md, mo.ui.*, etc.)+ return self._is_marimo_output_call(func)++ # All other expressions (constants, names, attributes, operations) are flagged+ return True++ def _is_marimo_output_call(self, func: ast.expr) -> bool:+ """Check if a call is a marimo output function (mo.md, mo.ui.*, etc.).++ Excludes control flow and side-effect calls like mo.stop() and mo.output.*.+ """+ if isinstance(func, ast.Attribute):+ # Direct mo.* calls (mo.md, mo.Html, etc.)+ if isinstance(func.value, ast.Name) and func.value.id == "mo":+ # Exclude mo.stop()+ if func.attr == "stop":+ return False+ return True++ # mo.ui.* or other nested mo.* calls+ if isinstance(func.value, ast.Attribute):+ if (+ isinstance(func.value.value, ast.Name)+ and func.value.value.id == "mo"+ ):+ # Exclude mo.output.* calls (append, replace, clear)+ if func.value.attr == "output":+ return False+ return True++ return False++ async def _report_diagnostic(+ self, node: ast.stmt, cell: CellDef, ctx: RuleContext, stmt_type: str+ ) -> None:+ """Report a diagnostic for a branch with trailing expressions."""+ message = (+ f"The {stmt_type} has branches ending with expressions that won't be displayed. "+ "marimo can only display the last expression if it is unnested. "+ "If this was intentional, consider assigning to a dummy variable: `_ = ...`"+ )++ diagnostic = Diagnostic(+ message=message,+ line=cell.lineno + node.lineno - 1,+ column=node.col_offset + 1,+ )++ await ctx.add_diagnostic(diagnostic)diff --git a/mkdocs.yml b/mkdocs.ymlindex 945d4a0075..009cc394f8 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -103,6 +103,7 @@ nav:- Setup cell dependencies: guides/lint_rules/rules/setup_cell_dependencies.md- Syntax error: guides/lint_rules/rules/invalid_syntax.md- Self Import: guides/lint_rules/rules/self_import.md+ - Branch expression: guides/lint_rules/rules/branch_expression.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.mddiff --git a/tests/_lint/snapshots/branch_expression_errors.txt b/tests/_lint/snapshots/branch_expression_errors.txtnew file mode 100644index 0000000000..7e04c01ae9--- /dev/null+++ b/tests/_lint/snapshots/branch_expression_errors.txt@@ -0,0 +1,27 @@+error[branch-expression]: The if statement has branches ending with expressions that won't be displayed. marimo can only display the last expression if it is unnested. If this was intentional, consider assigning to a dummy variable: `_ = ...`+ --> tests/_lint/test_files/branch_expression.py:13:1+ 13 | x = input("What's your name?") # prefer mo.ui.input in real cases :)+ 14 | if len(x) > 20:+ | ^+ 15 | invalid = True++error[branch-expression]: The if statement has branches ending with expressions that won't be displayed. marimo can only display the last expression if it is unnested. If this was intentional, consider assigning to a dummy variable: `_ = ...`+ --> tests/_lint/test_files/branch_expression.py:25:1+ 25 | # multi if+ 26 | if not invalid:+ | ^+ 27 | mo.md(f"User: {x}")++error[branch-expression]: The if statement has branches ending with expressions that won't be displayed. marimo can only display the last expression if it is unnested. If this was intentional, consider assigning to a dummy variable: `_ = ...`+ --> tests/_lint/test_files/branch_expression.py:37:1+ 37 | # Single if+ 38 | if invalid:+ | ^+ 39 | mo.md("Run the cell again to try again")++error[branch-expression]: The match statement has branches ending with expressions that won't be displayed. marimo can only display the last expression if it is unnested. If this was intentional, consider assigning to a dummy variable: `_ = ...`+ --> tests/_lint/test_files/branch_expression.py:54:1+ 54 | # match and constant cases+ 55 | match len(x):+ | ^+ 56 | case 1:diff --git a/tests/_lint/test_files/branch_expression.py b/tests/_lint/test_files/branch_expression.pynew file mode 100644index 0000000000..3d8689ae0a--- /dev/null+++ b/tests/_lint/test_files/branch_expression.py@@ -0,0 +1,122 @@+import marimo++__generated_with = "0.18.0"+app = marimo.App(width="medium")++with app.setup:+ import marimo as mo+++def _():+ # Standard branch+ x = input("What's your name?") # prefer mo.ui.input in real cases :)+ if len(x) > 20:+ invalid = True+ mo.md("Your name is very long.")+ else:+ invalid = False+ mo.md(f"Nice to meet you {x}")+ return invalid, x+++def _(invalid, x):+ # multi if+ if not invalid:+ mo.md(f"User: {x}")+ elif len(x) < 30:+ mo.md(f"Invalid: {x}")+ else:+ mo.md(f"Very Invalid: {x}")+ return+++def _(invalid):+ # Single if+ if invalid:+ mo.md("Run the cell again to try again")+ return+++def _(invalid, x):+ # Multiply nested cases+ if not invalid:+ if x == "name":+ mo.md("Your name probably isn't name")+ return+++def _(x):+ # match and constant cases+ match len(x):+ case 1:+ "Too Short!"+ case _:+ "Maybe reasonable"+ return+++def _(invalid):+ # Negative case: print() should NOT be flagged+ if invalid:+ print("Debug message")+ else:+ print("Another debug message")+ return+++def _(invalid, mo):+ # Negative case: mo.output.append() should NOT be flagged+ if invalid:+ mo.output.append(mo.md("Error!"))+ else:+ mo.output.append(mo.md("Success!"))+ return+++def _(invalid, mo):+ # Negative case: mo.stop() should NOT be flagged+ if invalid:+ mo.stop(True)+ return+++def _(invalid):+ import logging+ # Negative case: logging calls should NOT be flagged+ if invalid:+ logging.info("Invalid input")+ else:+ logging.debug("Valid input")+ return+++def _(invalid):+ import sys+ # Negative case: sys.stdout.write() should NOT be flagged+ if invalid:+ sys.stdout.write("Error\n")+ else:+ sys.stderr.write("Warning\n")+ return+++def _(invalid, mo):+ # Negative case: mo.output.replace() should NOT be flagged+ if invalid:+ mo.output.replace(mo.md("Replaced!"))+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_lint/test_snapshot.py b/tests/_lint/test_snapshot.pyindex ed70dd32fe..f944b3af7e 100644--- a/tests/_lint/test_snapshot.py+++ b/tests/_lint/test_snapshot.py@@ -241,3 +241,20 @@ def test_markdown_dedent_snapshot():error_output.append(error.format())snapshot("markdown_dedent_errors.txt", "\n".join(error_output))+++def test_branch_expression_snapshot():+ """Test snapshot for branch expression error."""+ file = "tests/_lint/test_files/branch_expression.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("branch_expression_errors.txt", "\n".join(error_output))