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
check + fix: Protections around user packges being used as site packages (#6638)
Dylan Madisetti32bd65811af5
diff --git a/docs/guides/lint_rules/index.md b/docs/guides/lint_rules/index.mdindex aee7f35473..eee07f992a 100644--- a/docs/guides/lint_rules/index.md+++ b/docs/guides/lint_rules/index.md@@ -33,6 +33,14 @@ These errors prevent notebook execution.| [MB004](rules/setup_cell_dependencies.md) | setup-cell-dependencies | Setup cell cannot have dependencies | ❌ || [MB005](rules/invalid_syntax.md) | invalid-syntax | Cell contains code that throws a SyntaxError on compilation | ❌ |+### ⚠️ Runtime Rules++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 | ❌ |+### ✨ Formatting RulesThese are style and formatting issues.diff --git a/docs/guides/lint_rules/rules/self_import.md b/docs/guides/lint_rules/rules/self_import.mdnew file mode 100644index 0000000000..dbea92060a--- /dev/null+++ b/docs/guides/lint_rules/rules/self_import.md@@ -0,0 +1,50 @@+# MR001: self-import++⚠️ **Runtime** ❌ Not Fixable++MR001: Importing a module with the same name as the file.++## What it does++Analyzes import statements in each cell to detect cases where the imported+module name matches the current file's name (without the .py extension).++## Why is this bad?++Importing a module with the same name as the file causes several issues:+- Python may attempt to import the current file instead of the intended module+- This can lead to circular import errors or unexpected behavior+- It makes the code confusing and hard to debug+- It can prevent the notebook from running correctly++This is a runtime issue because it can cause import confusion and unexpected behavior.++## Examples++**Problematic (in a file named `requests.py`):**+```python+import requests # Error: conflicts with file name+```++**Problematic (in a file named `math.py`):**+```python+from math import sqrt # Error: conflicts with file name+```++**Solution:**+```python+# Rename the file to something else, like my_requests.py+import requests # Now this works correctly+```++**Alternative Solution:**+```python+# Use a different approach that doesn't conflict+import urllib.request # Use alternative library+```++## References++- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)+- [Python Import System](https://docs.python.org/3/reference/import.html)+diff --git a/marimo/_lint/rules/__init__.py b/marimo/_lint/rules/__init__.pyindex e251c6504e..9d895d72f2 100644--- a/marimo/_lint/rules/__init__.py+++ b/marimo/_lint/rules/__init__.py@@ -2,13 +2,15 @@from marimo._lint.rules.base import LintRulefrom marimo._lint.rules.breaking import BREAKING_RULE_CODESfrom marimo._lint.rules.formatting import FORMATTING_RULE_CODES+from marimo._lint.rules.runtime import RUNTIME_RULE_CODESRULE_CODES: dict[str, type[LintRule]] = (- BREAKING_RULE_CODES | FORMATTING_RULE_CODES+ BREAKING_RULE_CODES | RUNTIME_RULE_CODES | FORMATTING_RULE_CODES)__all__ = ["RULE_CODES","BREAKING_RULE_CODES",+ "RUNTIME_RULE_CODES","FORMATTING_RULE_CODES",]diff --git a/marimo/_lint/rules/runtime/__init__.py b/marimo/_lint/rules/runtime/__init__.pynew file mode 100644index 0000000000..c28451c72e--- /dev/null+++ b/marimo/_lint/rules/runtime/__init__.py@@ -0,0 +1,12 @@+# Copyright 2025 Marimo. All rights reserved.+from marimo._lint.rules.base import LintRule+from marimo._lint.rules.runtime.self_import import SelfImportRule++RUNTIME_RULE_CODES: dict[str, type[LintRule]] = {+ "MR001": SelfImportRule,+}++__all__ = [+ "SelfImportRule",+ "RUNTIME_RULE_CODES",+]diff --git a/marimo/_lint/rules/runtime/self_import.py b/marimo/_lint/rules/runtime/self_import.pynew file mode 100644index 0000000000..720acf8ca2--- /dev/null+++ b/marimo/_lint/rules/runtime/self_import.py@@ -0,0 +1,144 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import os+from typing import TYPE_CHECKING++from marimo._lint.diagnostic import Diagnostic, Severity+from marimo._lint.rules.breaking.graph import GraphRule+from marimo._utils.site_packages import (+ has_local_conflict,+)++if TYPE_CHECKING:+ from marimo._lint.context import RuleContext+ from marimo._runtime.dataflow import DirectedGraph+++class SelfImportRule(GraphRule):+ """MR001: Importing a module with the same name as the file.++ This rule detects attempts to import a module that has the same name as the+ current file. This can cause import conflicts, circular import issues, and+ unexpected behavior where the file might try to import itself instead of+ the intended external module.++ ## What it does++ Analyzes import statements in each cell to detect cases where the imported+ module name matches the current file's name (without the .py extension).++ ## Why is this bad?++ Importing a module with the same name as the file causes several issues:+ - Python may attempt to import the current file instead of the intended module+ - This can lead to circular import errors or unexpected behavior+ - It makes the code confusing and hard to debug+ - It can prevent the notebook from running correctly++ This is a runtime issue because it can cause import confusion and unexpected behavior.++ ## Examples++ **Problematic (in a file named `requests.py`):**+ ```python+ import requests # Error: conflicts with file name+ ```++ **Problematic (in a file named `math.py`):**+ ```python+ from math import sqrt # Error: conflicts with file name+ ```++ **Solution:**+ ```python+ # Rename the file to something else, like my_requests.py+ import requests # Now this works correctly+ ```++ **Alternative Solution:**+ ```python+ # Use a different approach that doesn't conflict+ import urllib.request # Use alternative library+ ```++ ## References++ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)+ - [Python Import System](https://docs.python.org/3/reference/import.html)+ """++ code = "MR001"+ name = "self-import"+ description = "Importing a module with the same name as the file"+ severity = Severity.RUNTIME+ fixable = False++ async def _validate_graph(+ self, graph: DirectedGraph, ctx: RuleContext+ ) -> None:+ """Check for imports that conflict with the file name."""+ # Get the file name without extension+ if not ctx.notebook.filename:+ return++ file_name = os.path.basename(ctx.notebook.filename)+ if file_name.endswith(".py"):+ module_name = file_name[:-3]+ else:+ # For .md or other extensions, we can't determine conflicts+ return++ # Get directory containing the notebook file for local package checking+ notebook_dir = os.path.dirname(ctx.notebook.filename)++ await self._check_cells_for_conflicts(+ graph, ctx, module_name, file_name, notebook_dir+ )++ async def _check_cells_for_conflicts(+ self,+ graph: DirectedGraph,+ ctx: RuleContext,+ module_name: str,+ file_name: str,+ notebook_dir: str,+ ) -> None:+ """Check all cells for import conflicts using compiled cell data."""+ for cell_id, cell_impl in graph.cells.items():+ # Check imports from compiled cell data+ for variable, var_data_list in cell_impl.variable_data.items():+ for var_data in var_data_list:+ if var_data.import_data is None:+ continue++ import_data = var_data.import_data+ top_level_module = import_data.module.split(".")[0]+ fix_msg = f"Rename the file to avoid conflicts with the '{top_level_module}' module. "+ if top_level_module == module_name:+ # Standard self-import conflict+ message = f"Importing module '{top_level_module}' conflicts with file name '{file_name}'"+ # Check if there's a local file/package with the same name+ elif has_local_conflict(top_level_module, notebook_dir):+ # Module exists in site-packages - enhanced diagnostic+ message = (+ f"Importing module '{top_level_module}' conflicts "+ "with a module in site-packages, and may cause import ambiguity."+ )+ else:+ continue++ line, column = self._get_variable_line_info(+ cell_id, variable, ctx+ )+ diagnostic = Diagnostic(+ message=message,+ line=line,+ column=column,+ code=self.code,+ name=self.name,+ severity=self.severity,+ fixable=self.fixable,+ fix=fix_msg,+ )+ await ctx.add_diagnostic(diagnostic)diff --git a/marimo/_lint/visitors.py b/marimo/_lint/visitors.pyindex 4ae59440a4..71a444ecfd 100644--- a/marimo/_lint/visitors.py+++ b/marimo/_lint/visitors.py@@ -38,3 +38,27 @@ class VariableLineVisitor(ast.NodeVisitor):self.column_number = node.col_offset + 1returnself.generic_visit(node)++ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:+ """Visit ImportFrom nodes to find imported variable definitions."""+ for alias in node.names:+ if (+ alias.asname == self.target_variable+ or alias.name == self.target_variable+ ):+ self.line_number = node.lineno+ self.column_number = node.col_offset + 1+ return+ self.generic_visit(node)++ def visit_Import(self, node: ast.Import) -> None:+ """Visit Import nodes to find imported variable definitions."""+ for alias in node.names:+ if (+ alias.asname == self.target_variable+ or alias.name == self.target_variable+ ):+ self.line_number = node.lineno+ self.column_number = node.col_offset + 1+ return+ self.generic_visit(node)diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.pyindex 2329591569..477ec1a0ab 100644--- a/marimo/_output/formatters/formatters.py+++ b/marimo/_output/formatters/formatters.py@@ -38,6 +38,7 @@ from marimo._output.formatters.seaborn_formatters import SeabornFormatterfrom marimo._output.formatters.structures import StructuresFormatterfrom marimo._output.formatters.sympy_formatters import SympyFormatterfrom marimo._output.formatters.tqdm_formatters import TqdmFormatter+from marimo._utils.site_packages import is_local_moduleLOGGER = _loggers.marimo_logger()@@ -123,6 +124,10 @@ def patch_finder(if spec is None:return spec+ # Skip patching for local modules (not under site-packages)+ if is_local_module(spec):+ return spec+if spec.loader is not None and fullname in third_party_factories:# We're now in the process of importing a module with# an associated formatter factory. We'll hook into itsdiff --git a/marimo/_utils/site_packages.py b/marimo/_utils/site_packages.pynew file mode 100644index 0000000000..7f25142e1b--- /dev/null+++ b/marimo/_utils/site_packages.py@@ -0,0 +1,113 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import functools+import os+import pathlib+import site+from typing import Any+++def _getsitepackages() -> list[pathlib.Path]:+ try:+ # Try to get global site-packages (not available in virtual envs)+ site_packages_dirs = [pathlib.Path(p) for p in site.getsitepackages()]+ except AttributeError:+ # Fallback for virtual environments or restricted environments+ try:+ site_packages_dirs = [pathlib.Path(site.getusersitepackages())]+ except AttributeError:+ # Fallback to empty, and handle other ways.+ return []+ return site_packages_dirs+++def is_local_module(spec: Any) -> bool:+ """Check if a module is local (not under site-packages).++ Uses Python's site module to get actual site-packages directories,+ making it more robust across different Python installations and OS.+ """+ if spec is None or spec.origin is None:+ return True # Assume local if we can't determine++ if "site-packages" in spec.origin:+ return False++ module_path = pathlib.Path(spec.origin).resolve()+ site_packages_dirs = _getsitepackages()+ if not site_packages_dirs:+ # Ultimate fallback: use string matching+ return "site-packages" not in module_path.parts++ # Check if module is in any site-packages directory+ for site_dir in site_packages_dirs:+ try:+ if module_path.is_relative_to(site_dir):+ return False # Module is in site-packages+ except (OSError, ValueError):+ # Handle path resolution issues+ continue++ return True # Module is local+++def module_exists_in_site_packages(module_name: str) -> bool:+ """Check if a module exists in site-packages."""+ try:+ # Get all site-packages directories+ site_packages_dirs = site.getsitepackages()+ if hasattr(site, "getusersitepackages"):+ site_packages_dirs.append(site.getusersitepackages())++ for site_dir in site_packages_dirs:+ if not os.path.exists(site_dir):+ continue++ # Check for package directory+ package_dir = os.path.join(site_dir, module_name)+ if os.path.isdir(package_dir):+ return True++ # Check for .py file+ py_file = os.path.join(site_dir, f"{module_name}.py")+ if os.path.isfile(py_file):+ return True++ # Check for .pth files or other package indicators+ for entry in os.listdir(site_dir):+ module = entry.split("-", 1)[0]+ if module == module_name and (+ entry.endswith(".egg-info")+ or entry.endswith(".dist-info")+ or entry.endswith(".egg")+ ):+ return True++ except Exception:+ # If we can't check site-packages, assume it might exist+ return False++ return False+++def has_local_conflict(module_name: str, directory: str) -> bool:+ """Check if there's a local file or package that conflicts with the module name."""+ # Needs to have external module in site-packages to be a conflict+ if not module_exists_in_site_packages(module_name):+ return False++ # Check for local .py file with same name+ local_py = os.path.join(directory, f"{module_name}.py")+ if os.path.isfile(local_py):+ return True++ # Check for local package directory+ local_pkg = os.path.join(directory, module_name)+ if os.path.isdir(local_pkg) and os.path.isfile(+ os.path.join(local_pkg, "__init__.py")+ ):+ return True++ return Falsediff --git a/mkdocs.yml b/mkdocs.ymlindex 2ceade6f65..def9b30a01 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -102,6 +102,7 @@ nav:- 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+ - Self Import: guides/lint_rules/rules/self_import.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/scripts/generate_lint_docs.py b/scripts/generate_lint_docs.pyindex 000d3450fe..4cb78d2cb6 100644--- a/scripts/generate_lint_docs.py+++ b/scripts/generate_lint_docs.py@@ -30,7 +30,6 @@ from typing import Anyclass Severity(Enum):"""Severity levels for diagnostic errors."""FORMATTING = "formatting"- # Retained for future use: RUNTIME severity is intended for runtime-related lint rules.RUNTIME = "runtime"BREAKING = "breaking"@@ -111,40 +110,30 @@ def discover_all_rules() -> dict[str, RuleInfo]:# First, get the registered rule codes from the init filesbreaking_init = MARIMO_ROOT / "marimo" / "_lint" / "rules" / "breaking" / "__init__.py"formatting_init = MARIMO_ROOT / "marimo" / "_lint" / "rules" / "formatting" / "__init__.py"+ runtime_init = MARIMO_ROOT / "marimo" / "_lint" / "rules" / "runtime" / "__init__.py"registered_codes = set()+ def process(init_file: Path, prefix: str, registered_codes: set[str]) -> None:+ try:+ content = init_file.read_text()+ # Extract codes from BREAKING_RULE_CODES dictionary+ for line in content.split('\n'):+ if f'"{prefix}' in line and ':' in line:+ # Extract the code between quotes+ start = line.find(f'"{prefix}')+ if start != -1:+ end = line.find('"', start + 1)+ if end != -1:+ code = line[start + 1:end]+ registered_codes.add(code)+ except Exception as e:+ print(f"Warning: Could not parse rules init: {e}")+# Parse the breaking rules init file- try:- content = breaking_init.read_text()- # Extract codes from BREAKING_RULE_CODES dictionary- for line in content.split('\n'):- if '"MB' in line and ':' in line:- # Extract the code between quotes- start = line.find('"MB')- if start != -1:- end = line.find('"', start + 1)- if end != -1:- code = line[start + 1:end]- registered_codes.add(code)- except Exception as e:- print(f"Warning: Could not parse breaking rules init: {e}")-- # Parse the formatting rules init file- try:- content = formatting_init.read_text()- # Extract codes from FORMATTING_RULE_CODES dictionary- for line in content.split('\n'):- if '"MF' in line and ':' in line:- # Extract the code between quotes- start = line.find('"MF')- if start != -1:- end = line.find('"', start + 1)- if end != -1:- code = line[start + 1:end]- registered_codes.add(code)- except Exception as e:- print(f"Warning: Could not parse formatting rules init: {e}")+ process(breaking_init, "MB", registered_codes)+ process(runtime_init, "MR", registered_codes)+ process(formatting_init, "MF", registered_codes)# Now discover rules from source filesrules_dir = MARIMO_ROOT / "marimo" / "_lint" / "rules"diff --git a/tests/_lint/snapshots/self_import_pandas_errors.txt b/tests/_lint/snapshots/self_import_pandas_errors.txtnew file mode 100644index 0000000000..2da4484bb1--- /dev/null+++ b/tests/_lint/snapshots/self_import_pandas_errors.txt@@ -0,0 +1,7 @@+error[self-import]: Importing module 'pandas' conflicts with file name 'pandas.py'+ --> tests/_lint/test_files/pandas.py:8:1+ 8 | def _():+ 9 | import pandas as pd # Should trigger MR001 if pandas exists in site-packages+ | ^+ 10 | return+hint: Rename the file to avoid conflicts with the 'pandas' module.diff --git a/tests/_lint/snapshots/self_import_requests_errors.txt b/tests/_lint/snapshots/self_import_requests_errors.txtnew file mode 100644index 0000000000..a63f50601e--- /dev/null+++ b/tests/_lint/snapshots/self_import_requests_errors.txt@@ -0,0 +1,15 @@+error[self-import]: Importing module 'requests' conflicts with file name 'requests.py'+ --> tests/_lint/test_files/requests.py:8:1+ 8 | def _():+ 9 | import requests # Should trigger MR001 - file will be named requests.py importing requests+ | ^+ 10 | return+hint: Rename the file to avoid conflicts with the 'requests' module.++error[self-import]: Importing module 'requests' conflicts with file name 'requests.py'+ --> tests/_lint/test_files/requests.py:15:1+ 15 | # Test different import style+ 16 | from requests import get+ | ^+ 17 | return+hint: Rename the file to avoid conflicts with the 'requests' module.diff --git a/tests/_lint/snapshots/transitive_site_import_errors.txt b/tests/_lint/snapshots/transitive_site_import_errors.txtnew file mode 100644index 0000000000..a7ad9acc9f--- /dev/null+++ b/tests/_lint/snapshots/transitive_site_import_errors.txt@@ -0,0 +1,15 @@+error[self-import]: Importing module 'pandas' conflicts with file name 'pandas.py'+ --> tests/_lint/test_files/pandas.py:8:1+ 8 | def _():+ 9 | import pandas as pd # Should trigger MR001 - conflicts with pandas in site-packages+ | ^+ 10 | return+hint: Rename the file to avoid conflicts with the 'pandas' module.++error[self-import]: Importing module 'pandas' conflicts with file name 'pandas.py'+ --> tests/_lint/test_files/pandas.py:15:1+ 15 | # Test a different import style+ 16 | from pandas import DataFrame+ | ^+ 17 | return+hint: Rename the file to avoid conflicts with the 'pandas' module.diff --git a/tests/_lint/test_files/module_shadow.py b/tests/_lint/test_files/module_shadow.pynew file mode 100644index 0000000000..34980c1add--- /dev/null+++ b/tests/_lint/test_files/module_shadow.py@@ -0,0 +1,21 @@+import marimo++__generated_with = "0.16.3"+app = marimo.App()+++def _():+ import requests # Should trigger MR001 - file will be named requests.py importing requests+ return+++def _():+ # Test different import style+ from requests import get+ return+++if __name__ == "__main__":+ app.run()\ No newline at end of filediff --git a/tests/_lint/test_files/self_import_conflict.py b/tests/_lint/test_files/self_import_conflict.pynew file mode 100644index 0000000000..5c1b7f95ed--- /dev/null+++ b/tests/_lint/test_files/self_import_conflict.py@@ -0,0 +1,22 @@+import marimo++__generated_with = "0.16.3"+app = marimo.App()+++def _():+ import pandas as pd # Should trigger MR001 if pandas exists in site-packages+ return+++def _():+ # Test that we can still define functions+ def my_function():+ return "pandas specific logic"+ return+++if __name__ == "__main__":+ app.run()\ No newline at end of filediff --git a/tests/_lint/test_files/test_transitive_site_import.py b/tests/_lint/test_files/test_transitive_site_import.pynew file mode 100644index 0000000000..a4c1a2f457--- /dev/null+++ b/tests/_lint/test_files/test_transitive_site_import.py@@ -0,0 +1,21 @@+import marimo++__generated_with = "0.16.3"+app = marimo.App()+++def _():+ import pandas as pd # Should trigger MR001 - conflicts with pandas in site-packages+ return+++def _():+ # Test a different import style+ from pandas import DataFrame+ return+++if __name__ == "__main__":+ app.run()\ No newline at end of filediff --git a/tests/_lint/test_runtime_errors_snapshot.py b/tests/_lint/test_runtime_errors_snapshot.pyindex 8203ee3602..f5abf61bef 100644--- a/tests/_lint/test_runtime_errors_snapshot.py+++ b/tests/_lint/test_runtime_errors_snapshot.py@@ -125,3 +125,85 @@ def test_star_import_snapshot():error_output.append(error.format())snapshot("star_import_errors.txt", "\n".join(error_output))+++def test_self_import_pandas_snapshot(tmp_path):+ """Test snapshot for self-import pandas error."""+ source_file = "tests/_lint/test_files/self_import_conflict.py"+ with open(source_file) as f:+ code = f.read()++ # Create file with conflicting name in temporary directory+ conflicting_file = tmp_path / "pandas.py"+ conflicting_file.write_text(code)++ notebook = parse_notebook(code, filepath=str(conflicting_file))+ errors = lint_notebook(notebook)++ # Format errors for snapshot - manually normalize paths to avoid tmp path differences+ error_output = []+ for error in errors:+ formatted = error.format()+ # Replace temporary path with expected test path for consistent snapshots+ # Normalize path separators to forward slashes for cross-platform compatibility+ normalized = formatted.replace(+ str(tmp_path), "tests/_lint/test_files"+ ).replace("\\", "/")+ error_output.append(normalized)++ snapshot("self_import_pandas_errors.txt", "\n".join(error_output))+++def test_transitive_site_import_snapshot(tmp_path):+ """Test snapshot for transitive site import error."""+ source_file = "tests/_lint/test_files/test_transitive_site_import.py"+ with open(source_file) as f:+ code = f.read()++ # Create file with conflicting name in temporary directory+ # This file imports pandas, so we need to create a pandas.py file to trigger the conflict+ conflicting_file = tmp_path / "pandas.py"+ conflicting_file.write_text(code)++ notebook = parse_notebook(code, filepath=str(conflicting_file))+ errors = lint_notebook(notebook)++ # Format errors for snapshot - manually normalize paths to avoid tmp path differences+ error_output = []+ for error in errors:+ formatted = error.format()+ # Replace temporary path with expected test path for consistent snapshots+ # Normalize path separators to forward slashes for cross-platform compatibility+ normalized = formatted.replace(+ str(tmp_path), "tests/_lint/test_files"+ ).replace("\\", "/")+ error_output.append(normalized)++ snapshot("transitive_site_import_errors.txt", "\n".join(error_output))+++def test_self_import_requests_snapshot(tmp_path):+ """Test snapshot for self-import requests error."""+ source_file = "tests/_lint/test_files/module_shadow.py"+ with open(source_file) as f:+ code = f.read()++ # Create file with conflicting name in temporary directory+ conflicting_file = tmp_path / "requests.py"+ conflicting_file.write_text(code)++ notebook = parse_notebook(code, filepath=str(conflicting_file))+ errors = lint_notebook(notebook)++ # Format errors for snapshot - manually normalize paths to avoid tmp path differences+ error_output = []+ for error in errors:+ formatted = error.format()+ # Replace temporary path with expected test path for consistent snapshots+ # Normalize path separators to forward slashes for cross-platform compatibility+ normalized = formatted.replace(+ str(tmp_path), "tests/_lint/test_files"+ ).replace("\\", "/")+ error_output.append(normalized)++ snapshot("self_import_requests_errors.txt", "\n".join(error_output))diff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.pyindex 8841484613..441369703e 100644--- a/tests/_output/formatters/test_formatters.py+++ b/tests/_output/formatters/test_formatters.py@@ -11,7 +11,9 @@ import pytestfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.df_formatters import polars_dot_to_mermaid-from marimo._output.formatters.formatters import register_formatters+from marimo._output.formatters.formatters import (+ register_formatters,+)from marimo._output.formatting import (Plain,as_dom_node,diff --git a/tests/_utils/test_site_packages.py b/tests/_utils/test_site_packages.pynew file mode 100644index 0000000000..a0535c6e9f--- /dev/null+++ b/tests/_utils/test_site_packages.py@@ -0,0 +1,96 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import pathlib+import site+from unittest.mock import Mock++from marimo._utils.site_packages import (+ has_local_conflict,+ is_local_module,+ module_exists_in_site_packages,+)+++def test_is_local_module() -> None:+ """Test is_local_module with various module specs."""+ # Test with None spec (should return True - assume local if unknown)+ assert is_local_module(None)++ # Test with spec that has None origin (should return True)+ spec_no_origin = Mock()+ spec_no_origin.origin = None+ assert is_local_module(spec_no_origin)++ # Test with local module (should return True - is local)+ spec_local = Mock()+ spec_local.origin = "/home/user/myproject/mymodule.py"+ assert is_local_module(spec_local)++ # Test with actual site-packages path if available+ try:+ site_packages_dirs = site.getsitepackages()+ if site_packages_dirs:+ # Use an actual site-packages directory for testing+ test_site_dir = site_packages_dirs[0]+ spec_site_packages = Mock()+ spec_site_packages.origin = str(+ pathlib.Path(test_site_dir) / "requests" / "__init__.py"+ )+ assert not is_local_module(spec_site_packages)+ except (AttributeError, IndexError):+ # Skip site-packages test if not available (e.g., in restricted environments)+ pass++ # Test edge cases with path resolution issues+ spec_bad_path = Mock()+ spec_bad_path.origin = (+ "/nonexistent/path/that/should/not/exist/__init__.py"+ )+ # Should return True (local) if path can't be resolved properly+ result = is_local_module(spec_bad_path)+ assert isinstance(result, bool) # Should handle gracefully+++def test_module_exists_in_site_packages() -> None:+ """Test module_exists_in_site_packages function."""+ # Test with a module that likely exists (if available)+ # Note: This may vary by environment, so we test the return type+ result = module_exists_in_site_packages("os")+ assert isinstance(result, bool)++ # Test with a module that definitely doesn't exist+ assert not module_exists_in_site_packages(+ "definitely_nonexistent_module_12345"+ )+++def test_has_local_conflict() -> None:+ """Test has_local_conflict function."""+ import os+ import tempfile++ with tempfile.TemporaryDirectory() as temp_dir:+ # Test with no local file - should return False+ assert not has_local_conflict("nonexistent_module", temp_dir)++ # Create a local Python file+ local_file = os.path.join(temp_dir, "test_module.py")+ with open(local_file, "w") as f:+ f.write("# test module")++ # This will only return True if test_module exists in site-packages+ # which it likely doesn't, so we just test that it returns a boolean+ result = has_local_conflict("test_module", temp_dir)+ assert isinstance(result, bool)++ # Create a local package directory+ package_dir = os.path.join(temp_dir, "test_package")+ os.makedirs(package_dir)+ init_file = os.path.join(package_dir, "__init__.py")+ with open(init_file, "w") as f:+ f.write("# test package")++ # Again, will depend on whether test_package exists in site-packages+ result = has_local_conflict("test_package", temp_dir)+ assert isinstance(result, bool)