|
| 1 | +# Copyright 2025 Marimo. All rights reserved. |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import os |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from marimo._lint.diagnostic import Diagnostic, Severity |
| 8 | +from marimo._lint.rules.breaking.graph import GraphRule |
| 9 | +from marimo._utils.site_packages import ( |
| 10 | + has_local_conflict, |
| 11 | +) |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from marimo._lint.context import RuleContext |
| 15 | + from marimo._runtime.dataflow import DirectedGraph |
| 16 | + |
| 17 | + |
| 18 | +class SelfImportRule(GraphRule): |
| 19 | + """MR001: Importing a module with the same name as the file. |
| 20 | +
|
| 21 | + This rule detects attempts to import a module that has the same name as the |
| 22 | + current file. This can cause import conflicts, circular import issues, and |
| 23 | + unexpected behavior where the file might try to import itself instead of |
| 24 | + the intended external module. |
| 25 | +
|
| 26 | + ## What it does |
| 27 | +
|
| 28 | + Analyzes import statements in each cell to detect cases where the imported |
| 29 | + module name matches the current file's name (without the .py extension). |
| 30 | +
|
| 31 | + ## Why is this bad? |
| 32 | +
|
| 33 | + Importing a module with the same name as the file causes several issues: |
| 34 | + - Python may attempt to import the current file instead of the intended module |
| 35 | + - This can lead to circular import errors or unexpected behavior |
| 36 | + - It makes the code confusing and hard to debug |
| 37 | + - It can prevent the notebook from running correctly |
| 38 | +
|
| 39 | + This is a runtime issue because it can cause import confusion and unexpected behavior. |
| 40 | +
|
| 41 | + ## Examples |
| 42 | +
|
| 43 | + **Problematic (in a file named `requests.py`):** |
| 44 | + ```python |
| 45 | + import requests # Error: conflicts with file name |
| 46 | + ``` |
| 47 | +
|
| 48 | + **Problematic (in a file named `math.py`):** |
| 49 | + ```python |
| 50 | + from math import sqrt # Error: conflicts with file name |
| 51 | + ``` |
| 52 | +
|
| 53 | + **Solution:** |
| 54 | + ```python |
| 55 | + # Rename the file to something else, like my_requests.py |
| 56 | + import requests # Now this works correctly |
| 57 | + ``` |
| 58 | +
|
| 59 | + **Alternative Solution:** |
| 60 | + ```python |
| 61 | + # Use a different approach that doesn't conflict |
| 62 | + import urllib.request # Use alternative library |
| 63 | + ``` |
| 64 | +
|
| 65 | + ## References |
| 66 | +
|
| 67 | + - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/) |
| 68 | + - [Python Import System](https://docs.python.org/3/reference/import.html) |
| 69 | + """ |
| 70 | + |
| 71 | + code = "MR001" |
| 72 | + name = "self-import" |
| 73 | + description = "Importing a module with the same name as the file" |
| 74 | + severity = Severity.RUNTIME |
| 75 | + fixable = False |
| 76 | + |
| 77 | + async def _validate_graph( |
| 78 | + self, graph: DirectedGraph, ctx: RuleContext |
| 79 | + ) -> None: |
| 80 | + """Check for imports that conflict with the file name.""" |
| 81 | + # Get the file name without extension |
| 82 | + if not ctx.notebook.filename: |
| 83 | + return |
| 84 | + |
| 85 | + file_name = os.path.basename(ctx.notebook.filename) |
| 86 | + if file_name.endswith(".py"): |
| 87 | + module_name = file_name[:-3] |
| 88 | + else: |
| 89 | + # For .md or other extensions, we can't determine conflicts |
| 90 | + return |
| 91 | + |
| 92 | + # Get directory containing the notebook file for local package checking |
| 93 | + notebook_dir = os.path.dirname(ctx.notebook.filename) |
| 94 | + |
| 95 | + await self._check_cells_for_conflicts( |
| 96 | + graph, ctx, module_name, file_name, notebook_dir |
| 97 | + ) |
| 98 | + |
| 99 | + async def _check_cells_for_conflicts( |
| 100 | + self, |
| 101 | + graph: DirectedGraph, |
| 102 | + ctx: RuleContext, |
| 103 | + module_name: str, |
| 104 | + file_name: str, |
| 105 | + notebook_dir: str, |
| 106 | + ) -> None: |
| 107 | + """Check all cells for import conflicts using compiled cell data.""" |
| 108 | + for cell_id, cell_impl in graph.cells.items(): |
| 109 | + # Check imports from compiled cell data |
| 110 | + for variable, var_data_list in cell_impl.variable_data.items(): |
| 111 | + for var_data in var_data_list: |
| 112 | + if var_data.import_data is None: |
| 113 | + continue |
| 114 | + |
| 115 | + import_data = var_data.import_data |
| 116 | + top_level_module = import_data.module.split(".")[0] |
| 117 | + fix_msg = f"Rename the file to avoid conflicts with the '{top_level_module}' module. " |
| 118 | + if top_level_module == module_name: |
| 119 | + # Standard self-import conflict |
| 120 | + message = f"Importing module '{top_level_module}' conflicts with file name '{file_name}'" |
| 121 | + # Check if there's a local file/package with the same name |
| 122 | + elif has_local_conflict(top_level_module, notebook_dir): |
| 123 | + # Module exists in site-packages - enhanced diagnostic |
| 124 | + message = ( |
| 125 | + f"Importing module '{top_level_module}' conflicts " |
| 126 | + "with a module in site-packages, and may cause import ambiguity." |
| 127 | + ) |
| 128 | + else: |
| 129 | + continue |
| 130 | + |
| 131 | + line, column = self._get_variable_line_info( |
| 132 | + cell_id, variable, ctx |
| 133 | + ) |
| 134 | + diagnostic = Diagnostic( |
| 135 | + message=message, |
| 136 | + line=line, |
| 137 | + column=column, |
| 138 | + code=self.code, |
| 139 | + name=self.name, |
| 140 | + severity=self.severity, |
| 141 | + fixable=self.fixable, |
| 142 | + fix=fix_msg, |
| 143 | + ) |
| 144 | + await ctx.add_diagnostic(diagnostic) |
0 commit comments