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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: `try` blocks delete context variable afterwards, but marimo still considers them refs or defs if used (#1571)
Dylan Madisetti428b688ff09f
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex 7ad19d614a..03a86eec35 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -54,6 +54,14 @@ class Block:return any(name == defn for defn in self.defs)+@dataclass+class ObscuredScope:+ """The scope in which a name is hidden."""++ # Variable id if this block hides a name+ obscured: Optional[str] = None++@dataclassclass RefData:"""Metadata about variables referenced but not defined by a cell"""@@ -67,6 +75,7 @@ class RefData:class ScopedVisitor(ast.NodeVisitor):def __init__(self, mangle_prefix: Optional[str] = None) -> None:self.block_stack: list[Block] = [Block()]+ self.obscured_scope_stack: list[ObscuredScope] = []# Mapping from referenced names to their metadataself._refs: dict[Name, RefData] = {}# Unique prefix used to mangle cell-local variable names@@ -188,6 +197,14 @@ class ScopedVisitor(ast.NodeVisitor):"""Pop a block from the block stack."""self.block_stack.pop()+ def _push_obscured_scope(self, obscured: Optional[str]) -> None:+ """Push scope onto the stack."""+ self.obscured_scope_stack.append(ObscuredScope(obscured=obscured))++ def _pop_obscured_scope(self) -> None:+ """Pop scope from the stack."""+ self.obscured_scope_stack.pop()+def generic_visit(self, node: ast.AST) -> None:"""Visits the children of node and manages the block stack.@@ -235,6 +252,24 @@ class ScopedVisitor(ast.NodeVisitor):self.visit(node.value)self.visit(node.key)self._pop_block()+ elif isinstance(node, ast.Try) or (+ sys.version_info >= (3, 11) and isinstance(node, ast.TryStar)+ ):+ if sys.version_info < (3, 11):+ assert isinstance(node, ast.Try)+ # "Try" nodes have "handlers" that introduce exception context+ # variables that are tied to the try block, and don't exist beyond+ # it.+ for stmt in node.body:+ self.visit(stmt)+ for handler in node.handlers:+ self._push_obscured_scope(obscured=handler.name)+ self.visit(handler)+ self._pop_obscured_scope()+ for stmt in node.orelse:+ self.visit(stmt)+ for stmt in node.finalbody:+ self.visit(stmt)elif sys.version_info >= (3, 12) and isinstance(node, ast.TypeAlias):self.visit(node.name)self._push_block(is_comprehension=False)@@ -350,6 +385,16 @@ class ScopedVisitor(ast.NodeVisitor):# are not tracked at the attribute level. The default behavior# with our implemented visitors does the right thing (foo.bar[.*]# generates a ref to foo if foo has not been def'd).+ #+ # NB: Nodes like "Try" nodes introduce variable names that do not exist+ # beyond their inner scope. We traverse blocks to see if the name is+ # "obscured" in this way.++ for scope in self.obscured_scope_stack:+ if node.id == scope.obscured:+ self.generic_visit(node)+ return+if isinstance(node.ctx, ast.Store):node.id = self._if_local_then_mangle(node.id)self._define(node.id, VariableData(kind="variable"))diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.pyindex ff76e24d08..ca8482c226 100644--- a/tests/_ast/test_visitor.py+++ b/tests/_ast/test_visitor.py@@ -706,6 +706,68 @@ def test_from_import_star() -> None:assert not v.variable_data+def test_try_block() -> None:+ code = "\n".join(+ [+ "f = 2",+ "try:",+ " v = 1 / 0",+ "except TypeError as e:",+ " err = e",+ " e = 0",+ " x = out_of_scope",+ " print(f'caught {type(e)} with nested {e.exceptions}')",+ "except OSError as f:",+ " err2 = f",+ " try:",+ " y = 1 / 0",+ " except ZeroDivisionError as g:",+ " err3 = g",+ "else:",+ " w = 1",+ "finally:",+ " z = 3",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ # T should not be among the refs or defs+ assert "out_of_scope" in v.refs+ assert "e" not in v.refs+ assert "f" not in v.refs+ assert "g" not in v.refs+ assert v.defs == set(["f", "v", "w", "x", "y", "z", "err", "err2", "err3"])++[email protected]("sys.version_info < (3, 11)")+def test_try_star_block() -> None:+ code = "\n".join(+ [+ "try:",+ (+ " raise ExceptionGroup('eg', "+ "[ValueError(1), TypeError(2), OSError(3)])"+ ),+ "except* TypeError as e:",+ " print(f'caught {type(e)} with nested {e.exceptions}')",+ "except* OSError as f:",+ " print(f'caught {type(f)} with nested {f.exceptions}')",+ "else:",+ " print('Type and Os not raised')",+ "finally:",+ " print('finally')",+ ]+ )+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ # T should not be among the refs or defs+ assert v.defs == set([])+ assert "e" not in v.refs+ assert "f" not in v.refs++@pytest.mark.skipif("sys.version_info < (3, 12)")def test_type_alias_scoped() -> None:expr = "type alias[T] = list[T]"diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 1b2b7d8159..443c289959 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -749,6 +749,57 @@ class TestExecution:assert not k.errorsassert k.globals["x"] == 10+ @staticmethod+ async def test_exception_not_captured(+ any_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ k = any_kernel++ await k.run(+ [+ er_1 := exec_req.get(+ """+ exc = None+ try:+ 1 / 0+ except ZeroDivisionError as exc:+ e = exc+ """+ ),+ ]+ )+ assert not k.errors+ assert "exc" not in k.globals+ assert "exc" not in k.graph.cells[er_1.cell_id].refs+ assert "exc" in k.graph.cells[er_1.cell_id].defs+ assert "e" in k.globals+ assert isinstance(k.globals["e"], ZeroDivisionError)++ @staticmethod+ async def test_exception_scope_not_captured(+ any_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ k = any_kernel++ await k.run(+ [+ er_1 := exec_req.get(+ """+ try:+ 1 / 0+ except ZeroDivisionError as exc:+ e = exc+ exc = e+ """+ ),+ ]+ )+ assert not k.errors+ assert "exc" not in k.globals+ assert "exc" not in k.graph.cells[er_1.cell_id].refs+ assert "exc" not in k.graph.cells[er_1.cell_id].defs+ assert "e" in k.globals+class TestStoredOutput:async def test_ui_element_in_output_stored(