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: lint rule for private imports (#10580)

Dylan Madisetti3a1b1dabc357
diff --git a/docs/guides/lint_rules/index.md b/docs/guides/lint_rules/index.md
index 96c48f9460..2a1df9476e 100644
--- a/docs/guides/lint_rules/index.md
+++ b/docs/guides/lint_rules/index.md
@@ -45,6 +45,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 | ⚠️ |
+| [MR004](rules/private_import_alias.md) | private-import-alias | Import aliased to a private (underscore-prefixed) name | ❌ |
### ✨ Formatting Rules
diff --git a/docs/guides/lint_rules/rules/private_import_alias.md b/docs/guides/lint_rules/rules/private_import_alias.md
new file mode 100644
index 0000000000..589b84e050
--- /dev/null
+++ b/docs/guides/lint_rules/rules/private_import_alias.md
@@ -0,0 +1,73 @@
+# MR004: private-import-alias
+
+⚠️ **Runtime** ❌ Not Fixable
+
+MR004: Import aliased to a private (underscore-prefixed) name.
+
+## What it does
+
+Scans import statements for an explicit `as` alias whose bound name starts
+with an underscore. This pattern is an undesirable but common workaround for
+marimo's global redefinition restriction with little tangible payoff.
+
+## Why is this bad?
+
+Aliasing an import to a private name doesn't give the benefits users
+expect from it:
+
+- Imported modules are registered in `sys.modules` regardless of the
+ name they're bound to, so marimo's private-variable cleanup doesn't
+ free any extra memory.
+- Common imports like `numpy`, `pandas`, and `os` are usually needed in
+ multiple cells, and giving them a private name defeats reuse while
+ adding clutter.
+
+If the goal is to avoid the import polluting cell-to-cell dependencies, the
+fix is a setup cell, or import only cell instead. Setup cells run once,
+ahead of every other cell, while import only cells don't trigger
+re-execution of dependent cells (imports resolve independently of the
+notebook's reactive dataflow). Both of these approaches are preferable to
+aliasing imports to private names. You may even consider import only setup
+cells!
+
+## Examples
+
+**Problematic:**
+```python
+import os as _os
+
+_os.listdir(".")
+```
+
+```python
+import os as _os
+
+_os.getcwd()
+```
+
+**Problematic:**
+```python
+from collections import OrderedDict as _OrderedDict
+```
+
+**Solution:**
+```python
+# In the notebook's setup cell
+# or any import only cell.
+import os
+from collections import OrderedDict
+```
+
+```python
+os.listdir(".")
+```
+
+```python
+os.getcwd()
+```
+
+## References
+
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+- [Setup cell](https://docs.marimo.io/guides/understanding_errors/setup/)
+
diff --git a/marimo/_lint/rules/__init__.py b/marimo/_lint/rules/__init__.py
index 840294f194..7c82495213 100644
--- a/marimo/_lint/rules/__init__.py
+++ b/marimo/_lint/rules/__init__.py
@@ -1,4 +1,9 @@
# Copyright 2026 Marimo. All rights reserved.
+"""Lint rules for marimo notebooks.
+
+See `development_docs/adding_lint_rules.md` for how to add a new rule.
+"""
+
from __future__ import annotations
from marimo._lint.rules.base import LintRule
diff --git a/marimo/_lint/rules/runtime/__init__.py b/marimo/_lint/rules/runtime/__init__.py
index 5c1d1a6eeb..874d976dfa 100644
--- a/marimo/_lint/rules/runtime/__init__.py
+++ b/marimo/_lint/rules/runtime/__init__.py
@@ -3,6 +3,9 @@ from __future__ import annotations
from marimo._lint.rules.base import LintRule
from marimo._lint.rules.runtime.branch_expression import BranchExpressionRule
+from marimo._lint.rules.runtime.private_import_alias import (
+ PrivateImportAliasRule,
+)
from marimo._lint.rules.runtime.reusable_definition_order import (
ReusableDefinitionOrderRule,
)
@@ -12,11 +15,13 @@ RUNTIME_RULE_CODES: dict[str, type[LintRule]] = {
"MR001": SelfImportRule,
"MR002": BranchExpressionRule,
"MR003": ReusableDefinitionOrderRule,
+ "MR004": PrivateImportAliasRule,
}
__all__ = [
"RUNTIME_RULE_CODES",
"BranchExpressionRule",
+ "PrivateImportAliasRule",
"ReusableDefinitionOrderRule",
"SelfImportRule",
]
diff --git a/marimo/_lint/rules/runtime/private_import_alias.py b/marimo/_lint/rules/runtime/private_import_alias.py
new file mode 100644
index 0000000000..36f0891b9e
--- /dev/null
+++ b/marimo/_lint/rules/runtime/private_import_alias.py
@@ -0,0 +1,174 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+from typing import TYPE_CHECKING
+
+from marimo._ast.parse import ast_parse
+from marimo._ast.variables import is_local
+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 PrivateImportAliasRule(LintRule):
+ """MR004: Import aliased to a private (underscore-prefixed) name.
+
+ This rule detects imports that are explicitly aliased to a name starting
+ with an underscore more than once, e.g. `import os as _os`.
+
+ ## What it does
+
+ Scans import statements for an explicit `as` alias whose bound name starts
+ with an underscore. This pattern is an undesirable but common workaround for
+ marimo's global redefinition restriction with little tangible payoff.
+
+ ## Why is this bad?
+
+ Aliasing an import to a private name doesn't give the benefits users
+ expect from it:
+
+ - Imported modules are registered in `sys.modules` regardless of the
+ name they're bound to, so marimo's private-variable cleanup doesn't
+ free any extra memory.
+ - Common imports like `numpy`, `pandas`, and `os` are usually needed in
+ multiple cells, and giving them a private name defeats reuse while
+ adding clutter.
+
+ If the goal is to avoid the import polluting cell-to-cell dependencies, the
+ fix is a setup cell, or import only cell instead. Setup cells run once,
+ ahead of every other cell, while import only cells don't trigger
+ re-execution of dependent cells (imports resolve independently of the
+ notebook's reactive dataflow). Both of these approaches are preferable to
+ aliasing imports to private names. You may even consider import only setup
+ cells!
+
+ ## Examples
+
+ **Problematic:**
+ ```python
+ import os as _os
+
+ _os.listdir(".")
+ ```
+
+ ```python
+ import os as _os
+
+ _os.getcwd()
+ ```
+
+ **Problematic:**
+ ```python
+ from collections import OrderedDict as _OrderedDict
+ ```
+
+ **Solution:**
+ ```python
+ # In the notebook's setup cell
+ # or any import only cell.
+ import os
+ from collections import OrderedDict
+ ```
+
+ ```python
+ os.listdir(".")
+ ```
+
+ ```python
+ os.getcwd()
+ ```
+
+ ## References
+
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+ - [Setup cell](https://docs.marimo.io/guides/understanding_errors/setup/)
+ """
+
+ code = "MR004"
+ name = "private-import-alias"
+ description = "Import aliased to a private (underscore-prefixed) name"
+ severity = Severity.RUNTIME
+ fixable = False
+
+ async def check(self, ctx: RuleContext) -> None:
+ """Check for private-aliased imports repeated across cells."""
+ occurrences: dict[
+ tuple[str, ...], list[tuple[CellDef, ast.alias]]
+ ] = {}
+ for cell in ctx.notebook.cells:
+ if not cell.code.strip():
+ continue
+
+ try:
+ tree = ast_parse(cell.code)
+ except SyntaxError:
+ continue
+
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.Import, ast.ImportFrom)):
+ continue
+ for alias in node.names:
+ # `is_local` is the same notion of "private" that
+ # marimo's own name-mangling uses; it correctly excludes
+ # dunder-ish aliases (e.g. `__x`), which aren't given
+ # private-redefinition treatment.
+ if alias.asname is None or not is_local(alias.asname):
+ continue
+ key = self._import_key(node, alias)
+ occurrences.setdefault(key, []).append((cell, alias))
+
+ for entries in occurrences.values():
+ # Only flag if the same private alias is repeated across cells;
+ # a single occurrence isn't the redefinition workaround this
+ # rule is after.
+ if len(entries) < 2:
+ continue
+ await self._report(entries, ctx)
+
+ @staticmethod
+ def _import_key(
+ node: ast.Import | ast.ImportFrom, alias: ast.alias
+ ) -> tuple[str, ...]:
+ if isinstance(node, ast.ImportFrom):
+ module = f"{'.' * node.level}{node.module or ''}"
+ return ("from", module, alias.name, alias.asname or "")
+ return ("import", alias.name, alias.asname or "")
+
+ async def _report(
+ self,
+ entries: list[tuple[CellDef, ast.alias]],
+ ctx: RuleContext,
+ ) -> None:
+ # Point to every occurrence, like MultipleDefinitionsRule does for
+ # repeated variable definitions.
+ lines = [cell.lineno + alias.lineno - 1 for cell, alias in entries]
+ columns = [
+ cell.col_offset + alias.col_offset + 1 for cell, alias in entries
+ ]
+ _, alias = entries[0]
+
+ fix = (
+ "This private import is repeated across multiple cells: "
+ "consolidate the imports and drop the underscore. "
+ "Consider moving the import into a setup cell (`with "
+ "app.setup:`) or an import only cell"
+ )
+
+ diagnostic = Diagnostic(
+ message=(
+ f"Import of '{alias.name}' is aliased to the private "
+ f"name '{alias.asname}' in multiple cells."
+ ),
+ line=lines,
+ column=columns,
+ code=self.code,
+ name=self.name,
+ severity=self.severity,
+ fixable=self.fixable,
+ fix=fix,
+ )
+ await ctx.add_diagnostic(diagnostic)
diff --git a/mkdocs.yml b/mkdocs.yml
index 55d321833a..8a25d12a73 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -208,6 +208,7 @@ nav:
- 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
+ - Private import alias: guides/lint_rules/rules/private_import_alias.md
- Incompatible import: guides/lint_rules/rules/incompatible_import.md
- Unsafe system call: guides/lint_rules/rules/unsafe_system_call.md
- Incompatible package: guides/lint_rules/rules/incompatible_package.md
diff --git a/tests/_lint/snapshots/private_import_alias_errors.txt b/tests/_lint/snapshots/private_import_alias_errors.txt
new file mode 100644
index 0000000000..7579be97a2
--- /dev/null
+++ b/tests/_lint/snapshots/private_import_alias_errors.txt
@@ -0,0 +1,25 @@
+error[private-import-alias]: Import of 'os' is aliased to the private name '_os' in multiple cells.
+ --> tests/_lint/test_files/private_import_alias.py:6:8
+ 6 | with app.setup:
+ 7 | import os as _os
+ | ^
+ 8 |
+ ...
+ 12 | # Repeated: same `os as _os` as the setup cell above
+ 13 | import os as _os
+ | ^
+ 14 |
+hint: This private import is repeated across multiple cells: consolidate the imports and drop the underscore. Consider moving the import into a setup cell (`with app.setup:`) or an import only cell
+
+error[private-import-alias]: Import of 'OrderedDict' is aliased to the private name '_OrderedDict' in multiple cells.
+ --> tests/_lint/test_files/private_import_alias.py:28:25
+ 28 | def _():
+ 29 | from collections import OrderedDict as _OrderedDict
+ | ^
+ 30 |
+ ...
+ 36 | # Repeated: same `OrderedDict as _OrderedDict` as the cell above
+ 37 | from collections import OrderedDict as _OrderedDict
+ | ^
+ 38 |
+hint: This private import is repeated across multiple cells: consolidate the imports and drop the underscore. Consider moving the import into a setup cell (`with app.setup:`) or an import only cell
diff --git a/tests/_lint/test_files/private_import_alias.py b/tests/_lint/test_files/private_import_alias.py
new file mode 100644
index 0000000000..50a7980555
--- /dev/null
+++ b/tests/_lint/test_files/private_import_alias.py
@@ -0,0 +1,68 @@
+import marimo
+
+__generated_with = "0.24.0"
+app = marimo.App()
+
+with app.setup:
+ import os as _os
+
+
+def _():
+ # Repeated: same `os as _os` as the setup cell above
+ import os as _os
+
+ _os.getcwd()
+ return
+
+
+def _():
+ # Negative case: only occurs once, should NOT be flagged
+ import json as _json
+
+ return
+
+
+def _():
+ from collections import OrderedDict as _OrderedDict
+
+ return
+
+
+def _():
+ # Repeated: same `OrderedDict as _OrderedDict` as the cell above
+ from collections import OrderedDict as _OrderedDict
+
+ return
+
+
+def _():
+ # Negative case: plain import should NOT be flagged
+ import sys
+
+ return
+
+
+def _():
+ # Negative case: no alias, just a module named with a leading
+ # underscore, should NOT be flagged
+ import _thread
+
+ return
+
+
+def _():
+ # Negative case: aliasing to a public name should NOT be flagged
+ import numpy as np
+
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_lint/test_private_import_alias.py b/tests/_lint/test_private_import_alias.py
new file mode 100644
index 0000000000..6b9e931969
--- /dev/null
+++ b/tests/_lint/test_private_import_alias.py
@@ -0,0 +1,186 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._ast.parse import parse_notebook
+from tests._lint.utils import lint_notebook
+
+
+def _mr004_diagnostics(code: str):
+ notebook = parse_notebook(code, filepath="test.py")
+ return [d for d in lint_notebook(notebook) if d.code == "MR004"]
+
+
+def test_flags_import_repeated_across_cells():
+ code = """import marimo
+
+__generated_with = "0.18.0"
+app = marimo.App()
+
+
+def _():
+ import os as _os
+ return
+
+
+def _():
+ import os as _os
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+ diagnostics = _mr004_diagnostics(code)
+ assert len(diagnostics) == 1
+ assert "_os" in diagnostics[0].message
+ # Points to both occurrences, like MultipleDefinitionsRule.
+ assert len(diagnostics[0].line) == 2
+
+
+def test_flags_import_from_repeated_across_cells():
+ code = """import marimo
+
+__generated_with = "0.18.0"
+app = marimo.App()
+
+
+def _():
+ from collections import OrderedDict as _OrderedDict
+ return
+
+
+def _():
+ from collections import OrderedDict as _OrderedDict
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+ diagnostics = _mr004_diagnostics(code)
+ assert len(diagnostics) == 1
+ assert "_OrderedDict" in diagnostics[0].message
+ assert len(diagnostics[0].line) == 2
+
+
+def test_no_false_positive_for_single_occurrence():
+ code = """import marimo
+
+__generated_with = "0.18.0"
+app = marimo.App()
+
+
+def _():
+ import os as _os
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+ assert _mr004_diagnostics(code) == []
+
+
+def test_no_false_positive_for_plain_import():
+ code = """import marimo
+
+__generated_with = "0.18.0"
+app = marimo.App()
+
+
+def _():
+ import os
+ return
+
+
+def _():
+ import os
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+ assert _mr004_diagnostics(code) == []
+
+
+def test_no_false_positive_for_module_named_with_underscore():
+ code = """import marimo
+
+__generated_with = "0.18.0"
+app = marimo.App()
+
+
+def _():
+ import _thread
+ return
+
+
+def _():
+ import _thread
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+ assert _mr004_diagnostics(code) == []
+
+
+def test_no_false_positive_for_public_alias():
+ code = """import marimo
+
+__generated_with = "0.18.0"
+app = marimo.App()
+
+
+def _():
+ import numpy as np
+ return
+
+
+def _():
+ import numpy as np
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+ assert _mr004_diagnostics(code) == []
+
+
+def test_flags_repeat_across_setup_and_regular_cell():
+ """The setup cell isn't special-cased; a repeat there still counts."""
+ code = """import marimo
+
+__generated_with = "0.18.0"
+app = marimo.App()
+
+with app.setup:
+ import os as _os
+
+
+def _():
+ import os as _os
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+ diagnostics = _mr004_diagnostics(code)
+ assert len(diagnostics) == 1
+ assert len(diagnostics[0].line) == 2
diff --git a/tests/_lint/test_rule_selector.py b/tests/_lint/test_rule_selector.py
index 678d3a1483..8514c57ed2 100644
--- a/tests/_lint/test_rule_selector.py
+++ b/tests/_lint/test_rule_selector.py
@@ -28,7 +28,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) == 8 # 5 MB + 3 MR
+ assert len(rules) == 9 # 5 MB + 4 MR
def test_select_all(self):
rules = resolve_rules({"select": ["ALL"]})
diff --git a/tests/_lint/test_snapshot.py b/tests/_lint/test_snapshot.py
index c078b1e45f..420d2990e1 100644
--- a/tests/_lint/test_snapshot.py
+++ b/tests/_lint/test_snapshot.py
@@ -260,6 +260,22 @@ def test_branch_expression_snapshot():
snapshot("branch_expression_errors.txt", "\n".join(error_output))
+def test_private_import_alias_snapshot():
+ """Test snapshot for private import alias error."""
+ file = "tests/_lint/test_files/private_import_alias.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("private_import_alias_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"