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: traceback should contain line number, stack trace (#652)

Akshay Agrawalcaa23a5e2d4b
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index beecc68dad..d3d602cb00 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -4,6 +4,7 @@ import inspect
import io
import linecache
import os
+import re
import sys
import textwrap
import token as token_types
@@ -26,9 +27,18 @@ def code_key(code: str) -> int:
return hash(code)
-def get_filename(basename: str) -> str:
- """Get a temporary Python filename that ends with basename."""
- return os.path.join(get_tmpdir(), basename + ".py")
+def cell_id_from_filename(filename: str) -> Optional[CellId_t]:
+ """Parse cell id from filename."""
+ matches = re.findall(r"__marimo__cell_([0-9]+)", filename)
+ if matches:
+ return str(matches[0])
+ return None
+
+
+def get_filename(cell_id: CellId_t, suffix: str = "") -> str:
+ """Get a temporary Python filename that encodes the cell id in it."""
+ basename = f"__marimo__cell_{cell_id}"
+ return os.path.join(get_tmpdir(), basename + suffix + ".py")
def cache(filename: str, code: str) -> None:
@@ -41,11 +51,7 @@ def cache(filename: str, code: str) -> None:
)
-def compile_cell(
- code: str,
- cell_id: CellId_t,
- basename: Optional[str] = None,
-) -> Cell:
+def compile_cell(code: str, cell_id: CellId_t) -> Cell:
module = ast.parse(code, mode="exec")
if not module.body:
# either empty code or just comments
@@ -72,9 +78,9 @@ def compile_cell(
expr = "None"
# store the cell's code in Python's linecache so debuggers can find it
- basename = f"cell_{cell_id}" if basename is None else basename
- body_filename = get_filename(basename)
- last_expr_filename = get_filename(basename + "_output")
+ body_filename = get_filename(cell_id)
+ last_expr_filename = get_filename(cell_id, suffix="_output")
+ # cache the entire cell's code
cache(body_filename, code)
if sys.version_info >= (3, 9):
# ast.unparse only available >= 3.9
@@ -82,7 +88,6 @@ def compile_cell(
last_expr_filename,
ast.unparse(expr) if not isinstance(expr, str) else "None",
)
-
body = compile(module, body_filename, mode="exec")
last_expr = compile(expr, last_expr_filename, mode="eval")
diff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.py
index 7a1657fc49..c0fab35568 100644
--- a/marimo/_runtime/cell_runner.py
+++ b/marimo/_runtime/cell_runner.py
@@ -1,7 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import re
import sys
import traceback
from collections.abc import Container
@@ -9,6 +8,7 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional
from marimo._ast.cell import CellId_t, execute_cell
+from marimo._ast.compiler import cell_id_from_filename
from marimo._runtime import dataflow
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
@@ -21,14 +21,6 @@ def cell_filename(cell_id: CellId_t) -> str:
return f"<cell-{cell_id}>"
-def cell_id_from_filename(filename: str) -> Optional[CellId_t]:
- """Parses cell id from filename."""
- matches = re.findall(r"<cell-([0-9]+)>", filename)
- if matches:
- return str(matches[0])
- return None
-
-
def format_traceback(graph: dataflow.DirectedGraph) -> str:
"""Formats the current exception on the stack."""
# all three values are guaranteed to be non-None because an
diff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.py
index a9e9bcce56..be9de65925 100644
--- a/tests/_ast/test_compiler.py
+++ b/tests/_ast/test_compiler.py
@@ -97,3 +97,10 @@ class TestCellFactory:
cf = compiler.cell_factory(f, cell_id="0")
assert cf.cell.defs == {"x"}
assert cf.cell.refs == {"y"}
+
+
+def test_cell_id_from_filename() -> None:
+ assert compiler.cell_id_from_filename(compiler.get_filename("0")) == "0"
+ assert compiler.cell_id_from_filename(compiler.get_filename("2")) == "2"
+ assert compiler.cell_id_from_filename(compiler.get_filename("23")) == "23"
+ assert compiler.cell_id_from_filename("random_file.py") is None
diff --git a/tests/_runtime/test_cell_runner.py b/tests/_runtime/test_cell_runner.py
index 2a55618d96..e3508bd77f 100644
--- a/tests/_runtime/test_cell_runner.py
+++ b/tests/_runtime/test_cell_runner.py
@@ -1,4 +1,5 @@
# Copyright 2024 Marimo. All rights reserved.
+from marimo._runtime.capture import capture_stderr
from marimo._runtime.cell_runner import Runner
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -14,3 +15,29 @@ def test_cell_output(k: Kernel, exec_req: ExecReqProvider) -> None:
run_result = runner.run(er.cell_id)
# last expression of cell is output
assert run_result.output == 123
+
+
+def test_traceback_includes_lineno(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ # Raise an exception and test that the runner generates a traceback that
+ # includes the line number where the exception was raised
+ #
+ # first run the cell to populate the graph
+ k.run(
+ [
+ er := exec_req.get(
+ """
+ x = 0
+ raise ValueError
+ """
+ )
+ ]
+ )
+
+ runner = Runner(
+ cell_ids=set(k.graph.cells.keys()), graph=k.graph, glbls=k.globals
+ )
+ with capture_stderr() as buffer:
+ runner.run(er.cell_id)
+ assert "line 3" in buffer.getvalue()