Skip to content

Commit

Permalink
Improve reporting of unparsable code
Browse files Browse the repository at this point in the history
Show the unparseable code in the error message when directly running a
notebook via the python command.

Fixes #2265
  • Loading branch information
pentlander committed Jan 18, 2025
1 parent b7d78be commit a4b0b3a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ marimo/_lsp/

.vscode
.vercel
.idea

.marimo.toml
.mypy_cache/
Expand Down
25 changes: 22 additions & 3 deletions marimo/_ast/app.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -155,6 +157,7 @@ def __init__(self, **kwargs: Any) -> None:
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
Expand Down Expand Up @@ -222,14 +225,30 @@ def _unparsable_cell(
name,
CellConfig.from_dict(config),
)
self._unparsable_code.append(code)
self._unparsable = True

def _maybe_initialize(self) -> None:
if self._unparsable:
errors = []
for code in self._unparsable_code:
try:
ast.parse(dedent(code))
except SyntaxError as e:
error_line = e.text
error_marker = " " * (e.offset - 1) + "^"
err = (
f"{error_line}"
f"{error_marker}\n"
f"{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
Expand Down
3 changes: 2 additions & 1 deletion tests/_ast/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,9 @@ def one() -> tuple[int]:
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:
Expand Down

0 comments on commit a4b0b3a

Please sign in to comment.