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.

fix: Handle 'import *' correctly for marimo check (#6425)

Dylan Madisetti1687b0c32bdc
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 6f46878ff7..1fa721eb6c 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -263,7 +263,9 @@ class ScopedVisitor(ast.NodeVisitor):
else:
return name
- def _get_alias_name(self, node: ast.alias) -> str:
+ def _get_alias_name(
+ self, node: ast.alias, import_node: ast.ImportFrom | None = None
+ ) -> str:
"""Get the string name of an imported alias.
Mangles the "as" name if it's a local variable.
@@ -281,11 +283,15 @@ class ScopedVisitor(ast.NodeVisitor):
# Don't mangle - user has no control over package name
basename = node.name.split(".")[0]
if basename == "*":
- line = (
- f"line {node.lineno}"
+ # Use the ImportFrom node's line number for consistency
+ line_num = (
+ import_node.lineno
+ if import_node and hasattr(import_node, "lineno")
+ else node.lineno
if hasattr(node, "lineno")
- else "line ..."
+ else None
)
+ line = f"line {line_num}" if line_num else "line ..."
raise ImportStarError(
f"{line} SyntaxError: Importing symbols with `import *` "
"is not allowed in marimo."
@@ -973,7 +979,7 @@ class ScopedVisitor(ast.NodeVisitor):
# we don't recurse into the alias nodes, since we define the
# aliases here
for alias_node in node.names:
- variable_name = self._get_alias_name(alias_node)
+ variable_name = self._get_alias_name(alias_node, import_node=node)
original_name = alias_node.name
self._define(
None,
diff --git a/marimo/_cli/print.py b/marimo/_cli/print.py
index 15ab443deb..53db2d24ca 100644
--- a/marimo/_cli/print.py
+++ b/marimo/_cli/print.py
@@ -78,6 +78,13 @@ def cyan(text: str, bold: bool = False) -> str:
return prefix + text + "\033[0m"
+def light_blue(text: str, bold: bool = False) -> str:
+ if not _USE_COLOR:
+ return text
+ prefix = "\033[96m" if not bold else "\033[1;96m"
+ return prefix + text + "\033[0m"
+
+
def muted(text: str) -> str:
# Use dark gray (37 is white, 2 is dim) which is more widely supported than 90
return "\033[37;2m" + text + "\033[0m" if _USE_COLOR else text
diff --git a/marimo/_lint/formatter.py b/marimo/_lint/formatter.py
index 303acd44cb..7525faf3cb 100644
--- a/marimo/_lint/formatter.py
+++ b/marimo/_lint/formatter.py
@@ -5,7 +5,7 @@ import os
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
-from marimo._cli.print import bold, cyan, red, yellow
+from marimo._cli.print import bold, cyan, light_blue, red, yellow
from marimo._lint.diagnostic import Severity
if TYPE_CHECKING:
@@ -109,5 +109,5 @@ class FullFormatter(DiagnosticFormatter):
previous_line = end_line
if diagnostic.fix:
- context_lines.append(cyan("info: ") + bold(diagnostic.fix))
+ context_lines.append(light_blue("hint: ") + bold(diagnostic.fix))
return f"{header}\n" + "\n".join(context_lines)
diff --git a/marimo/_lint/rules/breaking/syntax_error.py b/marimo/_lint/rules/breaking/syntax_error.py
index 558f26d217..3da7d48bd6 100644
--- a/marimo/_lint/rules/breaking/syntax_error.py
+++ b/marimo/_lint/rules/breaking/syntax_error.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
from marimo._ast.compiler import (
ir_cell_factory,
)
+from marimo._ast.errors import ImportStarError
from marimo._lint.diagnostic import Diagnostic, Severity
from marimo._lint.rules.base import LintRule
from marimo._schemas.serialization import UnparsableCell
@@ -13,6 +14,16 @@ from marimo._types.ids import CellId_t
if TYPE_CHECKING:
from marimo._lint.context import RuleContext
+ from marimo._schemas.serialization import CellDef
+
+IMPORT_STAR_ERROR_MESSAGE = (
+ "Importing symbols with `import *` is not allowed in marimo."
+)
+IMPORT_STAR_HINT = (
+ "Star imports are incompatible with marimo's reactive execution. Use "
+ "'import module' and access members with dot notation instead. See: "
+ "https://docs.marimo.io/guides/understanding_errors/import_star/"
+)
class SyntaxErrorRule(LintRule):
@@ -95,6 +106,17 @@ class SyntaxErrorRule(LintRule):
cell_id=CellId_t("Hbol"),
filename=ctx.notebook.filename,
)
+ # Technically a SyntaxError subclass
+ except ImportStarError as e:
+ line, column = _handle_import_star_error(e, cell)
+ await ctx.add_diagnostic(
+ Diagnostic(
+ message=IMPORT_STAR_ERROR_MESSAGE,
+ line=line,
+ column=column,
+ fix=IMPORT_STAR_HINT,
+ )
+ )
except SyntaxError as e:
message = f"{e.msg}"
await ctx.add_diagnostic(
@@ -107,10 +129,40 @@ class SyntaxErrorRule(LintRule):
)
+def _handle_import_star_error(
+ e: ImportStarError, cell: CellDef
+) -> tuple[int, int]:
+ """Handle ImportStarError and extract correct line number and clean message."""
+ import re
+
+ message_str = str(e)
+ # The message format is "line {lineno} SyntaxError: ..." Extract the
+ # relative line number and compute actual line
+ actual_line = None
+ if "..." not in message_str:
+ line_match = re.match(r"line (\d+)", message_str)
+ if line_match:
+ relative_line = int(line_match.group(1))
+ actual_line = cell.lineno + relative_line - 1
+ if actual_line is None:
+ actual_line = cell.lineno
+ # Find the * in the cell source
+ star_index = cell.code.find("*")
+ if star_index != -1:
+ # Count newlines before the star to get the line number
+ actual_line += cell.code[:star_index].count("\n")
+
+ # Clean message without "SyntaxError:" prefix
+ column = getattr(e, "offset", 1) or 1
+
+ return actual_line, column
+
+
def _get_known_hints(message: str) -> str | None:
if message == "'return' outside function":
return (
- "marimo cells are not normal Python functions; treat cell bodies"
- " as top-level code, or use `@app.function` to define a pure function."
+ "marimo cells are not normal Python functions; treat cell bodies "
+ "as top-level code, or use `@app.function` to define a pure "
+ "function."
)
return None
diff --git a/tests/_lint/snapshots/multiple_definitions_errors.txt b/tests/_lint/snapshots/multiple_definitions_errors.txt
index 63f1c2ddd0..07814e1507 100644
--- a/tests/_lint/snapshots/multiple_definitions_errors.txt
+++ b/tests/_lint/snapshots/multiple_definitions_errors.txt
@@ -9,4 +9,4 @@ critical[multiple-definitions]: Variable 'x' is defined in multiple cells
16 | x = 2 # This should trigger MR001 - multiple definitions
| ^
17 | return
-info: Variables must be unique across cells. Alternatively, they can be private with an underscore prefix (i.e. `_x`.)
\ No newline at end of file
+hint: Variables must be unique across cells. Alternatively, they can be private with an underscore prefix (i.e. `_x`.)
\ No newline at end of file
diff --git a/tests/_lint/snapshots/star_import_errors.txt b/tests/_lint/snapshots/star_import_errors.txt
new file mode 100644
index 0000000000..0d1e7706d6
--- /dev/null
+++ b/tests/_lint/snapshots/star_import_errors.txt
@@ -0,0 +1,21 @@
+critical[invalid-syntax]: Importing symbols with `import *` is not allowed in marimo.
+ --> tests/_lint/test_files/star_import.py:9:1
+ 9 | # This should trigger MB005 - syntax error with star import hint
+ 10 | from math import *
+ | ^
+ 11 | result = sin(pi / 2)
+hint: Star imports are incompatible with marimo's reactive execution. Use 'import module' and access members with dot notation instead. See: https://docs.marimo.io/guides/understanding_errors/import_star/
+critical[invalid-syntax]: Importing symbols with `import *` is not allowed in marimo.
+ --> tests/_lint/test_files/star_import.py:16:1
+ 16 | def _():
+ 17 | from pandas import *
+ | ^
+ 18 | df = DataFrame({"a": [1, 2, 3]})
+hint: Star imports are incompatible with marimo's reactive execution. Use 'import module' and access members with dot notation instead. See: https://docs.marimo.io/guides/understanding_errors/import_star/
+critical[invalid-syntax]: Importing symbols with `import *` is not allowed in marimo.
+ --> tests/_lint/test_files/star_import.py:44:1
+ 44 | # comments
+ 45 | from os import *
+ | ^
+ 46 | current_dir = getcwd()
+hint: Star imports are incompatible with marimo's reactive execution. Use 'import module' and access members with dot notation instead. See: https://docs.marimo.io/guides/understanding_errors/import_star/
\ No newline at end of file
diff --git a/tests/_lint/snapshots/syntax_errors.txt b/tests/_lint/snapshots/syntax_errors.txt
index f9c943b8fe..93a44cb845 100644
--- a/tests/_lint/snapshots/syntax_errors.txt
+++ b/tests/_lint/snapshots/syntax_errors.txt
@@ -10,4 +10,4 @@ critical[invalid-syntax]: 'return' outside function
16 | return tickers
| ^
17 | return
-info: marimo cells are not normal Python functions; treat cell bodies as top-level code, or use `@app.function` to define a pure function.
\ No newline at end of file
+hint: marimo cells are not normal Python functions; treat cell bodies as top-level code, or use `@app.function` to define a pure function.
\ No newline at end of file
diff --git a/tests/_lint/test_files/star_import.py b/tests/_lint/test_files/star_import.py
new file mode 100644
index 0000000000..b08494bbce
--- /dev/null
+++ b/tests/_lint/test_files/star_import.py
@@ -0,0 +1,51 @@
+import marimo
+
+__generated_with = "0.15.2"
+app = marimo.App()
+
+
+def _():
+ # This should trigger MB005 - syntax error with star import hint
+ from math import *
+ result = sin(pi / 2)
+ return result,
+
+
+def _():
+ from pandas import *
+ df = DataFrame({"a": [1, 2, 3]})
+ return df,
+
+
+def _():
+ # This should NOT trigger syntax error - normal import
+ import numpy as np
+ arr = np.array([1, 2, 3])
+ return arr,
+
+
+def _():
+ # This should NOT trigger syntax error - specific imports
+ from typing import List, Dict
+ data: List[Dict[str, int]] = [{"x": 1}, {"y": 2}]
+ return data,
+
+
+def _():
+ # Another star import but
+ # Pad out import statement
+ # with
+ # super
+ # comments
+ from os import *
+ current_dir = getcwd()
+ return current_dir,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_lint/test_runtime_errors_snapshot.py b/tests/_lint/test_runtime_errors_snapshot.py
index 33f3dce9a5..8203ee3602 100644
--- a/tests/_lint/test_runtime_errors_snapshot.py
+++ b/tests/_lint/test_runtime_errors_snapshot.py
@@ -108,3 +108,20 @@ def test_syntax_errors_snapshot():
error_output.append(error.format())
snapshot("syntax_errors.txt", "\n".join(error_output))
+
+
+def test_star_import_snapshot():
+ """Test snapshot for star import syntax errors with enhanced hints."""
+ file = "tests/_lint/test_files/star_import.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("star_import_errors.txt", "\n".join(error_output))