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.

Improve reporting of unparsable code (#3500)

Alex Pentland9bc61db3693e
diff --git a/.gitignore b/.gitignore
index 5bbefcb172..9a3912a742 100644
--- a/.gitignore
+++ b/.gitignore
@@ -111,6 +111,7 @@ marimo/_lsp/
.vscode
.vercel
+.idea
.marimo.toml
.mypy_cache/
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index dd051b0138..2bdb0570c8 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -1,8 +1,10 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import ast
import inspect
from dataclasses import asdict, dataclass, field
+from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
@@ -155,6 +157,7 @@ class App:
self._execution_context: ExecutionContext | None = None
self._runner = dataflow.Runner(self._graph)
+ self._unparsable_code: list[str] = []
self._unparsable = False
self._initialized = False
# injection hook set by contexts like tests such that script traces are
@@ -222,14 +225,30 @@ class App:
name,
CellConfig.from_dict(config),
)
+ self._unparsable_code.append(code)
self._unparsable = True
def _maybe_initialize(self) -> None:
if self._unparsable:
+ errors: list[str] = []
+ for code in self._unparsable_code:
+ try:
+ ast.parse(dedent(code))
+ except SyntaxError as e:
+ error_line = e.text
+ error_marker: str = (
+ " " * (e.offset - 1) + "^"
+ if e.offset is not None
+ else ""
+ )
+ err = f"{error_line}{error_marker}\n{e.msg}"
+ errors.append(err)
+ syntax_errors = "\n-----\n".join(errors)
+
raise UnparsableError(
- "This notebook has cells with syntax errors, "
- "so it cannot be initialized."
- )
+ f"The notebook '{self._filename}' has cells with syntax errors, "
+ + f"so it cannot be initialized:\n {syntax_errors}"
+ ) from None
if self._initialized:
return
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 6ec2123d5a..eeb7de1435 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -159,8 +159,9 @@ class TestApp:
app._unparsable_cell("_ _")
app._unparsable_cell("_ _", name="foo")
- with pytest.raises(UnparsableError):
+ with pytest.raises(UnparsableError) as e:
app.run()
+ e.match("_ _")
@staticmethod
def test_init_not_rewritten_as_local() -> None: