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
Store metadata about a cell's variables (including imports) (#651)
Akshay Agrawal20117cc04822
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 432ad59db3..61065ca830 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -17,7 +17,7 @@ from typing import (cast,)-from marimo._ast.visitor import Name+from marimo._ast.visitor import Name, VariableDatafrom marimo._utils.deep_merge import deep_mergeCellId_t = str@@ -79,6 +79,8 @@ class Cell:mod: ast.Moduledefs: set[Name]refs: set[Name]+ # metadata about definitions+ variable_data: dict[Name, VariableData]deleted_refs: set[Name]body: Optional[CodeType]last_expr: Optional[CodeType]@@ -111,6 +113,15 @@ class Cell:def disabled_transitively(self) -> bool:return self.status == "disabled-transitively"+ @property+ def imported_modules(self) -> set[Name]:+ """Return a set of the modules imported by this cell."""+ return set(+ data.module+ for _, data in self.variable_data.items()+ if data.module is not None+ )+def set_status(self, status: CellStatusType) -> None:from marimo._messaging.ops import CellOpfrom marimo._runtime.context import (@@ -164,7 +175,7 @@ def cell_function(n_args += 1parameters = list(signature.parameters.keys())- return_names = sorted(cell.defs)+ return_names = sorted(defn for defn in cell.defs)@functools.wraps(f)def func(*args: Any, **kwargs: Any) -> tuple[Any, ...]:diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex b76099804b..beecc68dad 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -55,6 +55,7 @@ def compile_cell(mod=module,defs=set(),refs=set(),+ variable_data={},deleted_refs=set(),body=None,last_expr=None,@@ -93,6 +94,11 @@ def compile_cell(mod=module,defs=glbls,refs=v.refs,+ variable_data={+ name: v.variable_data[name]+ for name in glbls+ if name in v.variable_data+ },deleted_refs=v.deleted_refs,body=body,last_expr=last_expr,diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex 66a7dccdcd..f55076d0ac 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -4,12 +4,21 @@ from __future__ import annotationsimport astimport sysfrom dataclasses import dataclass, field-from typing import Optional+from typing import Literal, Optionalfrom uuid import uuid4Name = str+@dataclass+class VariableData:+ kind: Literal["function", "class", "import", "variable"] = "variable"++ # For kind == import+ module: Optional[str] = None+ import_level: Optional[int] = None++def is_local(name: str) -> bool:return name.startswith("_") and not name.startswith("__")@@ -22,9 +31,14 @@ class Block:defs: set[Name] = field(default_factory=set)# Names defined with the global keywordglobal_names: set[Name] = field(default_factory=set)+ # Map from defined names to metadata about their variables+ variable_data: dict[Name, VariableData] = field(default_factory=dict)# Comprehensions have special scoping rulesis_comprehension: bool = False+ def is_defined(self, name: str) -> bool:+ return any(name == defn for defn in self.defs)+@dataclassclass RefData:@@ -48,6 +62,16 @@ class ScopedVisitor(ast.NodeVisitor):else mangle_prefix)+ @property+ def defs(self) -> set[Name]:+ """Get all global defs."""+ return self.block_stack[0].defs++ @property+ def variable_data(self) -> dict[Name, VariableData]:+ """Get data accompanying globals."""+ return self.block_stack[0].variable_data+@propertydef refs(self) -> set[Name]:"""Names referenced but not defined."""@@ -67,9 +91,37 @@ class ScopedVisitor(ast.NodeVisitor):else:return name+ def _get_alias_name(self, node: ast.alias) -> str:+ """Get the string name of an imported alias++ NB: We disallow `import *` because Python only allows+ star imports at module-level, but we store cells as functions.+ """+ if node.asname is None:+ # Imported name without an "as" clause. Examples:+ # import [a.b.c] - we define a+ # from foo import [a] - we define a+ # from foo import [*] - we don't define anything+ #+ # Note:+ # Don't mangle - user has no control over package name+ basename = node.name.split(".")[0]+ if basename == "*":+ line = (+ f"line {node.lineno}"+ if hasattr(node, "lineno")+ else "line ..."+ )+ raise SyntaxError(+ f"{line} SyntaxError: `import *` is not allowed in marimo."+ )+ return basename+ else:+ return self._if_local_then_mangle(node.asname)+def _is_defined(self, identifier: str) -> bool:"""Check if `identifier` is defined in any block."""- return any(identifier in block.defs for block in self.block_stack)+ return any(block.is_defined(identifier) for block in self.block_stack)def _add_ref(self, name: Name, deleted: bool) -> None:"""Register a referenced name."""@@ -82,12 +134,13 @@ class ScopedVisitor(ast.NodeVisitor):"""Remove a referenced name."""del self._refs[name]- def _define(self, name: Name) -> None:- """Define a name in the current block.+ def _define_in_block(+ self, name: Name, variable_data: VariableData, block_idx: int+ ) -> None:+ """Define a name in a given block."""- Names created with the global keyword are added to the top-level- (global scope) block.- """+ self.block_stack[block_idx].defs.add(name)+ self.block_stack[block_idx].variable_data[name] = variable_data# If `name` is added to the top-level block, it is also evicted from# any captured refs (if present) --- this handles cases where a name is# encountered and captured before it is declared, such as in@@ -97,8 +150,6 @@ class ScopedVisitor(ast.NodeVisitor):# print(x)# x = 0# ```- block_idx = 0 if name in self.block_stack[-1].global_names else -1- self.block_stack[block_idx].defs.add(name)if (name in self._refsand self.block_stack[block_idx] in self._refs[name].parent_blocks@@ -106,6 +157,15 @@ class ScopedVisitor(ast.NodeVisitor):# `name` was used as a capture, not a referenceself._remove_ref(name)+ def _define(self, name: Name, variable_data: VariableData) -> None:+ """Define a name in the current block.++ Names created with the global keyword are added to the top-level+ (global scope) block.+ """+ block_idx = 0 if name in self.block_stack[-1].global_names else -1+ self._define_in_block(name, variable_data, block_idx=block_idx)+def _push_block(self, is_comprehension: bool) -> None:"""Push a block onto the block stack."""self.block_stack.append(Block(is_comprehension=is_comprehension))@@ -114,11 +174,6 @@ class ScopedVisitor(ast.NodeVisitor):"""Pop a block from the block stack."""self.block_stack.pop()- @property- def defs(self) -> set[Name]:- """Get all global defs."""- return self.block_stack[0].defs-def generic_visit(self, node: ast.AST) -> None:"""Visits the children of node and manages the block stack.@@ -180,22 +235,22 @@ class ScopedVisitor(ast.NodeVisitor):# ClassDef and FunctionDef nodes don't have ast.Name nodes as childrendef visit_ClassDef(self, node: ast.ClassDef) -> None:node.name = self._if_local_then_mangle(node.name)- self._define(Name(node.name))+ self._define(node.name, VariableData(kind="class"))self.generic_visit(node)def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:node.name = self._if_local_then_mangle(node.name)- self._define(node.name)+ self._define(node.name, VariableData(kind="function"))self.generic_visit(node)def visit_FunctionDef(self, node: ast.FunctionDef) -> None:node.name = self._if_local_then_mangle(node.name)- self._define(node.name)+ self._define(node.name, VariableData(kind="function"))self.generic_visit(node)def visit_arg(self, node: ast.arg) -> None:node.arg = self._if_local_then_mangle(node.arg)- self._define(node.arg)+ self._define(node.arg, VariableData(kind="variable"))if node.annotation is not None:self.visit(node.annotation)@@ -248,13 +303,21 @@ class ScopedVisitor(ast.NodeVisitor):if self.block_stack[-1].is_comprehension and isinstance(node.target, ast.Name):- for block in reversed(self.block_stack):+ for block_idx, block in reversed(+ list(enumerate(self.block_stack))+ ):+ # go up the block stack until we find the first+ # non-comprehension blockif not block.is_comprehension:node.target.id = self._if_local_then_mangle(node.target.id,ignore_scope=(block == self.block_stack[0]),)- block.defs.add(node.target.id)+ self._define_in_block(+ node.target.id,+ VariableData(kind="variable"),+ block_idx=block_idx,+ )breakelse:self.generic_visit(node)@@ -275,7 +338,7 @@ class ScopedVisitor(ast.NodeVisitor):# generates a ref to foo if foo has not been def'd).if isinstance(node.ctx, ast.Store):node.id = self._if_local_then_mangle(node.id)- self._define(node.id)+ self._define(node.id, VariableData(kind="variable"))elif (isinstance(node.ctx, ast.Load)and not self._is_defined(node.id)@@ -293,9 +356,11 @@ class ScopedVisitor(ast.NodeVisitor):node.id, ignore_scope=True)for block in reversed(self.block_stack):- if block == self.block_stack[0] and mangled_name in block.defs:+ if block == self.block_stack[0] and block.is_defined(+ mangled_name+ ):node.id = mangled_name- elif node.id in block.defs:+ elif block.is_defined(node.id):breakself.generic_visit(node)@@ -312,35 +377,29 @@ class ScopedVisitor(ast.NodeVisitor):# that needs to be tracked?# Import and ImportFrom statements have symbol names in alias nodesdef visit_alias(self, node: ast.alias) -> None:- """Visiting names in import statements-- NB: We disallow `import *` because Python only allows- star imports at module-level, but we store cells as functions.- """- if node.asname is None:- # imported name, no "as" clause; examples:- # import [a.b.c] - we define a- # from foo import [a] - we define a- # from foo import [*] - we don't define anything- #- # Note:- # Don't mangle - user has no control over package name- basename = node.name.split(".")[0]- if basename == "*":- line = (- f"line {node.lineno}"- if hasattr(node, "lineno")- else "line ..."- )- raise SyntaxError(- f"{line} SyntaxError: `import *` is not allowed in marimo."- )- self._define(basename)- else:- node.asname = self._if_local_then_mangle(node.asname)- self._define(node.asname)+ """Visiting names in import statements"""+ name = self._get_alias_name(node)+ # Extract module name+ # - import a.b.c as d: module name a is different from the alias name d+ # - import a.b.c: module name a is equal to the alias name a+ module = node.name.split(".")[0] if node.asname is not None else name+ self._define(name, VariableData(kind="import", module=module))self.generic_visit(node)+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:+ # module should not be None here, but appease the type checker+ module = node.module.split(".")[0] if node.module is not None else None+ imported_names = [self._get_alias_name(alias) for alias in node.names]+ # we don't recurse into the alias nodes, since we define the+ # aliases here+ for name in imported_names:+ self._define(+ name,+ VariableData(+ kind="import", module=module, import_level=node.level+ ),+ )+if sys.version_info >= (3, 10):# Match statements were introduced in Python 3.10#@@ -352,7 +411,7 @@ class ScopedVisitor(ast.NodeVisitor):def visit_MatchAs(self, node: ast.MatchAs) -> None:if node.name is not None:node.name = self._if_local_then_mangle(node.name)- self._define(node.name)+ self._define(node.name, VariableData(kind="variable"))if node.pattern is not None:# pattern may contain additional MatchAs statements in itself.visit(node.pattern)@@ -360,7 +419,7 @@ class ScopedVisitor(ast.NodeVisitor):def visit_MatchMapping(self, node: ast.MatchMapping) -> None:if node.rest is not None:node.rest = self._if_local_then_mangle(node.rest)- self._define(node.rest)+ self._define(node.rest, VariableData(kind="variable"))for key in node.keys:self.visit(key)for pattern in node.patterns:@@ -369,13 +428,13 @@ class ScopedVisitor(ast.NodeVisitor):def visit_MatchStar(self, node: ast.MatchStar) -> None:if node.name is not None:node.name = self._if_local_then_mangle(node.name)- self._define(node.name)+ self._define(node.name, VariableData(kind="variable"))if sys.version_info >= (3, 12):def visit_TypeVar(self, node: ast.TypeVar) -> None:# node.name is a str, not an ast.Name node- self._define(node.name)+ self._define(node.name, VariableData(kind="variable"))if isinstance(node.bound, tuple):for name in node.bound:self.visit(name)@@ -384,8 +443,8 @@ class ScopedVisitor(ast.NodeVisitor):def visit_ParamSpec(self, node: ast.ParamSpec) -> None:# node.name is a str, not an ast.Name node- self._define(node.name)+ self._define(node.name, VariableData(kind="variable"))def visit_TypeVarTuple(self, node: ast.TypeVarTuple) -> None:# node.name is a str, not an ast.Name node- self._define(node.name)+ self._define(node.name, VariableData(kind="variable"))diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.pyindex 693cea4fb8..56ae2a456b 100644--- a/marimo/_plugins/ui/_core/registry.py+++ b/marimo/_plugins/ui/_core/registry.py@@ -49,6 +49,7 @@ class UIElementRegistry:def _register_bindings(self, object_id: UIElementId) -> None:kernel = get_context().kernel+ # Get all variable names that are bound to this UI elementnames = set([namediff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.pyindex f0999c83ea..bf87bc9d0e 100644--- a/marimo/_runtime/dataflow.py+++ b/marimo/_runtime/dataflow.py@@ -9,6 +9,7 @@ from typing import Optional, Tuplefrom marimo import _loggersfrom marimo._ast.cell import Cell, CellId_tfrom marimo._ast.compiler import code_key+from marimo._ast.visitor import NameEdge = Tuple[CellId_t, CellId_t]@@ -39,7 +40,7 @@ class DirectedGraph:siblings: dict[CellId_t, set[CellId_t]] = field(default_factory=dict)# A mapping from defs to the cells that define them- definitions: dict[str, set[CellId_t]] = field(default_factory=dict)+ definitions: dict[Name, set[CellId_t]] = field(default_factory=dict)# The set of cycles in the graphcycles: set[tuple[Edge, ...]] = field(default_factory=set)@@ -55,7 +56,14 @@ class DirectedGraph:cell_id in self.cells and code_key(code) == self.cells[cell_id].key)- def get_referring_cells(self, name: str) -> set[CellId_t]:+ def get_defining_cells(self, name: Name) -> set[CellId_t]:+ """Get all cells that define name.++ This is a singleton for well-formed graphs.+ """+ return self.definitions[name]++ def get_referring_cells(self, name: Name) -> set[CellId_t]:"""Get all cells that have a ref to `name`."""return set([cid for cid in self.cells if name in self.cells[cid].refs])@@ -258,13 +266,13 @@ class DirectedGraph:# `any` expressions using assignment expressions, but# that's a silly reason to make Python < 3.8 incompatible# with marimo.- def get_multiply_defined(self) -> Optional[str]:+ def get_multiply_defined(self) -> Optional[Name]:for name, definers in self.definitions.items():if len(definers) > 1:return namereturn None- def get_deleted_nonlocal_ref(self) -> Optional[str]:+ def get_deleted_nonlocal_ref(self) -> Optional[Name]:for cell in self.cells.values():for ref in cell.deleted_refs:if ref in self.definitions:diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 3695b652e7..1f4ce57335 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -21,7 +21,7 @@ from typing import Any, Callable, Iterator, Optionalfrom marimo import _loggersfrom marimo._ast.cell import CellConfig, CellId_tfrom marimo._ast.compiler import compile_cell-from marimo._ast.visitor import is_local+from marimo._ast.visitor import Name, is_localfrom marimo._config.config import configurefrom marimo._messaging.errors import (Error,@@ -320,7 +320,7 @@ class Kernel:return previous_children, errordef _delete_names(- self, names: Iterable[str], exclude_defs: set[str]+ self, names: Iterable[Name], exclude_defs: set[Name]) -> None:"""Delete `names` from kernel, except for `exclude_defs`"""for name in names:@@ -339,7 +339,7 @@ class Kernel:def _invalidate_cell_state(self,cell_id: CellId_t,- exclude_defs: Optional[set[str]] = None,+ exclude_defs: Optional[set[Name]] = None,deletion: bool = False,) -> None:"""Cleanup state associated with this cell.@@ -463,7 +463,7 @@ class Kernel:)# defs that we shouldn't remove from the graph- keep_alive_defs: set[str] = set()+ keep_alive_defs: set[Name] = set()for cid in list(semantic_errors.keys()):# If a cell was previously valid, don't invalidate it unless# we have to, ie, unless it is a descendant of a just-registered@@ -917,7 +917,7 @@ class Kernel:try:referring_cells.update(self.graph.get_referring_cells(name)- - self.graph.definitions[name]+ - self.graph.get_defining_cells(name))except Exception:# Internal marimo errordiff --git a/marimo/_runtime/validate_graph.py b/marimo/_runtime/validate_graph.pyindex efb3f441f1..da0ba599e3 100644--- a/marimo/_runtime/validate_graph.py+++ b/marimo/_runtime/validate_graph.py@@ -28,7 +28,7 @@ def check_for_multiple_definitions(for cid in defining_cells:errors[cid].append(MultipleDefinitionError(- name=name,+ name=str(name),cells=tuple(sorted(defining_cells - set([cid]))),))@@ -45,7 +45,7 @@ def check_for_delete_nonlocal(if name in graph.definitions:errors[cid].append(DeleteNonlocalError(- name=name,+ name=str(name),cells=tuple(graph.definitions[name]),))diff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.pyindex f0e5d7716a..a9e9bcce56 100644--- a/tests/_ast/test_compiler.py+++ b/tests/_ast/test_compiler.py@@ -20,10 +20,11 @@ class TestParseCell:@staticmethoddef test_local_variables() -> None:- code = "_, y = f(x)\ndef _foo():\n _bar = 0\nimport _secret_module"+ code = "_, y = f(x)\ndef _foo():\n _bar = 0\nimport _secret_module as module" # noqa: E501cell = compile_cell(code)- assert cell.defs == {"y"}+ assert cell.defs == {"module", "y"}assert cell.refs == {"f", "x"}+ assert cell.imported_modules == {"_secret_module"}@staticmethoddef test_dunder_dunder_excluded() -> None:@@ -43,8 +44,11 @@ class TestParseCell:def test_alias_underscored_name() -> None:code = "import _m as m"cell = compile_cell(code)+ # m is the imported name ...assert cell.defs == {"m"}assert cell.refs == set()+ # but _m is the module from which it was imported+ assert cell.imported_modules == {"_m"}@staticmethoddef test_ref_local_var() -> None:@@ -57,6 +61,17 @@ class TestParseCell:cell = compile_cell(code)assert cell.defs == {"f"}assert cell.refs == set()+ assert not cell.imported_modules++ @staticmethod+ def test_import() -> None:+ code = "from a.b.c import d; x = None"+ cell = compile_cell(code)+ # "d" is the imported name ...+ assert cell.defs == {"d", "x"}+ assert cell.refs == set()+ # but "a" is the module from which it was imported+ assert cell.imported_modules == {"a"}class TestCellFactory:diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.pyindex 61e7b5787f..c0f8d85952 100644--- a/tests/_ast/test_visitor.py+++ b/tests/_ast/test_visitor.py@@ -7,6 +7,7 @@ from inspect import cleandocimport pytestfrom marimo._ast import visitor+from marimo._ast.visitor import VariableDatadef test_assign_simple() -> None:@@ -16,6 +17,7 @@ def test_assign_simple() -> None:v.visit(mod)assert v.defs == set(["x"])assert v.refs == set()+ assert v.variable_data == {"x": VariableData(kind="variable")}def test_multiple_assign() -> None:@@ -25,6 +27,10 @@ def test_multiple_assign() -> None:v.visit(mod)assert v.defs == set(["x", "y"])assert v.refs == set()+ assert v.variable_data == {+ "x": VariableData(kind="variable"),+ "y": VariableData(kind="variable"),+ }def test_assign_multiple_statements() -> None:@@ -34,6 +40,10 @@ def test_assign_multiple_statements() -> None:v.visit(mod)assert v.defs == set(["x", "y"])assert v.refs == set()+ assert v.variable_data == {+ "x": VariableData(kind="variable"),+ "y": VariableData(kind="variable"),+ }def test_assign_attr() -> None:@@ -43,6 +53,7 @@ def test_assign_attr() -> None:v.visit(mod)assert v.defs == set()assert v.refs == set(["x"])+ assert not v.variable_datadef test_read_attr() -> None:@@ -52,6 +63,7 @@ def test_read_attr() -> None:v.visit(mod)assert v.defs == set()assert v.refs == set(["x"])+ assert not v.variable_datadef test_read_attr_of_defined_variable() -> None:@@ -61,6 +73,7 @@ def test_read_attr_of_defined_variable() -> None:v.visit(mod)assert v.defs == set(["x"])assert v.refs == set()+ assert v.variable_data == {"x": VariableData(kind="variable")}def test_assign_nested_attr() -> None:@@ -70,6 +83,7 @@ def test_assign_nested_attr() -> None:v.visit(mod)assert v.defs == set()assert v.refs == set(["x"])+ assert not v.variable_datadef test_read_nested_attr() -> None:@@ -79,6 +93,7 @@ def test_read_nested_attr() -> None:v.visit(mod)assert v.defs == set()assert v.refs == set(["x"])+ assert not v.variable_datadef test_assign_same_name() -> None:@@ -88,6 +103,7 @@ def test_assign_same_name() -> None:v.visit(mod)assert v.defs == set(["x"])assert v.refs == set(["x"])+ assert v.variable_data == {"x": VariableData(kind="variable")}expr = "(x := x)"v = visitor.ScopedVisitor()@@ -95,6 +111,7 @@ def test_assign_same_name() -> None:v.visit(mod)assert v.defs == set(["x"])assert v.refs == set(["x"])+ assert v.variable_data == {"x": VariableData(kind="variable")}expr = "x += x"v = visitor.ScopedVisitor()@@ -102,6 +119,7 @@ def test_assign_same_name() -> None:v.visit(mod)assert v.defs == set(["x"])assert v.refs == set(["x"])+ assert v.variable_data == {"x": VariableData(kind="variable")}expr = "def f(): x = x; return x"v = visitor.ScopedVisitor()@@ -109,6 +127,7 @@ def test_assign_same_name() -> None:v.visit(mod)assert v.defs == set(["f"])assert v.refs == set(["x"])+ assert v.variable_data == {"f": VariableData(kind="function")}expr = "class F(): x = x"v = visitor.ScopedVisitor()@@ -116,6 +135,7 @@ def test_assign_same_name() -> None:v.visit(mod)assert v.defs == set(["F"])assert v.refs == set(["x"])+ assert v.variable_data == {"F": VariableData(kind="class")}expr = "{x: x}"v = visitor.ScopedVisitor()@@ -123,6 +143,7 @@ def test_assign_same_name() -> None:v.visit(mod)assert v.defs == set()assert v.refs == set(["x"])+ assert not v.variable_datadef test_load_attr() -> None:@@ -132,6 +153,7 @@ def test_load_attr() -> None:v.visit(mod)assert v.defs == set()assert v.refs == set(["x"])+ assert not v.variable_datadef test_structured_assignment() -> None:@@ -142,6 +164,16 @@ def test_structured_assignment() -> None:names = set(["a", "b", "c", "d", "e", "f", "g", "h"])assert v.defs == namesassert v.refs == set()+ assert v.variable_data == {+ "a": VariableData(kind="variable"),+ "b": VariableData(kind="variable"),+ "c": VariableData(kind="variable"),+ "d": VariableData(kind="variable"),+ "e": VariableData(kind="variable"),+ "f": VariableData(kind="variable"),+ "g": VariableData(kind="variable"),+ "h": VariableData(kind="variable"),+ }def test_starred_assignment() -> None:@@ -151,6 +183,10 @@ def test_starred_assignment() -> None:v.visit(mod)assert v.defs == set(["a", "b"])assert v.refs == set()+ assert v.variable_data == {+ "a": VariableData(kind="variable"),+ "b": VariableData(kind="variable"),+ }def test_scope_does_not_leak() -> None:@@ -166,6 +202,9 @@ def test_scope_does_not_leak() -> None:v.visit(mod)assert v.defs == set(["foo"])assert v.refs == set("z")+ assert v.variable_data == {+ "foo": VariableData(kind="function"),+ }def test_nested_comprehensions() -> None:@@ -181,11 +220,13 @@ def test_nested_comprehensions() -> None:v.visit(mod)assert v.defs == set()assert v.refs == set(["range"])+ assert not v.variable_datadef test_walrus_leaks_to_global_in_comprehension() -> None:code = "\n".join([+ "def foo(): a","[(a := (i, (b := j))) for i in range(10) for j in range(i)]","{(c := (i, j)) for i in range(10) for j in range(i)}","{i: (d := j) for i in range(10) for j in range(i)}",@@ -194,8 +235,16 @@ def test_walrus_leaks_to_global_in_comprehension() -> None:v = visitor.ScopedVisitor()mod = ast.parse(code)v.visit(mod)- assert v.defs == set(["a", "b", "c", "d"])+ assert v.defs == set(["a", "b", "c", "d", "foo"])+ # "a" should not be a ref!assert v.refs == set(["range"])+ assert v.variable_data == {+ "a": VariableData(kind="variable"),+ "b": VariableData(kind="variable"),+ "c": VariableData(kind="variable"),+ "d": VariableData(kind="variable"),+ "foo": VariableData(kind="function"),+ }def test_nested_walrus_leaks_to_global_in_comprehension() -> None:@@ -205,6 +254,10 @@ def test_nested_walrus_leaks_to_global_in_comprehension() -> None:v.visit(mod)assert v.defs == set(["a", "b"])assert v.refs == set(["range"])+ assert v.variable_data == {+ "a": VariableData(kind="variable"),+ "b": VariableData(kind="variable"),+ }def test_pep572_walrus_comprehension_examples() -> None:@@ -214,6 +267,9 @@ def test_pep572_walrus_comprehension_examples() -> None:v.visit(mod)assert v.defs == set(["y"])assert v.refs == set(["input_data", "f"])+ assert v.variable_data == {+ "y": VariableData(kind="variable"),+ }code = "[[y := f(x), x/y] for x in range(5)]"v = visitor.ScopedVisitor()@@ -221,6 +277,9 @@ def test_pep572_walrus_comprehension_examples() -> None:v.visit(mod)assert v.defs == set(["y"])assert v.refs == set(["f", "range"])+ assert v.variable_data == {+ "y": VariableData(kind="variable"),+ }def test_walrus_in_comp_in_fn_block_does_not_leak_to_global() -> None:@@ -232,6 +291,9 @@ def test_walrus_in_comp_in_fn_block_does_not_leak_to_global() -> None:v.visit(mod)assert v.defs == set(["f"]) # x should _not_ leak to global scopeassert v.refs == set(["range"]) # x should leak to f's scope+ assert v.variable_data == {+ "f": VariableData(kind="function"),+ }def test_assignments_in_multiple_scopes() -> None:@@ -251,6 +313,11 @@ def test_assignments_in_multiple_scopes() -> None:v.visit(mod)assert v.defs == set(["a", "e", "foo"])assert v.refs == set()+ assert v.variable_data == {+ "a": VariableData(kind="variable"),+ "e": VariableData(kind="variable"),+ "foo": VariableData(kind="function"),+ }def test_function_with_args() -> None:@@ -266,6 +333,9 @@ def test_function_with_args() -> None:v.visit(mod)assert v.defs == set(["foo"])assert v.refs == set("z")+ assert v.variable_data == {+ "foo": VariableData(kind="function"),+ }def test_function_with_defaults() -> None:@@ -280,6 +350,9 @@ def test_function_with_defaults() -> None:v.visit(mod)assert v.defs == set(["foo"])assert v.refs == set(["x", "y", "a"])+ assert v.variable_data == {+ "foo": VariableData(kind="function"),+ }def test_async_function_def() -> None:@@ -296,6 +369,10 @@ def test_async_function_def() -> None:v.visit(mod)assert v.defs == set(["foo", "x"])assert v.refs == set("z")+ assert v.variable_data == {+ "foo": VariableData(kind="function"),+ "x": VariableData(kind="variable"),+ }def test_global_def() -> None:@@ -311,6 +388,10 @@ def test_global_def() -> None:v.visit(mod)assert v.defs == set(["foo", "x"])assert v.refs == set()+ assert v.variable_data == {+ "foo": VariableData(kind="function"),+ "x": VariableData(kind="variable"),+ }def test_global_ref() -> None:@@ -326,6 +407,9 @@ def test_global_ref() -> None:v.visit(mod)assert v.defs == set(["foo"])assert v.refs == set(["x", "print"])+ assert v.variable_data == {+ "foo": VariableData(kind="function"),+ }def test_nested_local_def_and_global_ref() -> None:@@ -343,6 +427,9 @@ def test_nested_local_def_and_global_ref() -> None:v.visit(mod)assert v.defs == set(["foo"])assert v.refs == set(["x", "print"])+ assert v.variable_data == {+ "foo": VariableData(kind="function"),+ }def test_call_ref() -> None:@@ -352,6 +439,7 @@ def test_call_ref() -> None:v.visit(mod)assert v.defs == set()assert v.refs == set(["foo"])+ assert not v.variable_datadef test_call_defined() -> None:@@ -367,6 +455,9 @@ def test_call_defined() -> None:v.visit(mod)assert v.defs == set(["foo"])assert v.refs == set()+ assert v.variable_data == {+ "foo": VariableData(kind="function"),+ }def test_mutation_generates_def() -> None:@@ -376,6 +467,9 @@ def test_mutation_generates_def() -> None:v.visit(mod)assert v.defs == set(["x"])assert v.refs == set()+ assert v.variable_data == {+ "x": VariableData(kind="variable"),+ }def test_captured_variables() -> None:@@ -473,6 +567,14 @@ def test_matchas() -> None:v.visit(mod)assert v.defs == set(["a", "b", "c", "d", "e", "f"])assert v.refs == set(["value"])+ assert v.variable_data == {+ "a": VariableData(kind="variable"),+ "b": VariableData(kind="variable"),+ "c": VariableData(kind="variable"),+ "d": VariableData(kind="variable"),+ "e": VariableData(kind="variable"),+ "f": VariableData(kind="variable"),+ }@pytest.mark.skipif("sys.version_info < (3, 10)")@@ -491,6 +593,9 @@ def test_matchstar() -> None:v.visit(mod)assert v.defs == set(["rest"])assert v.refs == set(["value"])+ assert v.variable_data == {+ "rest": VariableData(kind="variable"),+ }@pytest.mark.skipif("sys.version_info < (3, 10)")@@ -511,6 +616,10 @@ def test_matchmapping() -> None:v.visit(mod)assert v.defs == set(["a", "b"])assert v.refs == set(["value"])+ assert v.variable_data == {+ "a": VariableData(kind="variable"),+ "b": VariableData(kind="variable"),+ }def test_import_nested() -> None:@@ -520,6 +629,7 @@ def test_import_nested() -> None:v.visit(mod)assert v.defs == set(["a"])assert v.refs == set()+ assert v.variable_data["a"] == VariableData(kind="import", module="a")def test_import_as() -> None:@@ -529,6 +639,7 @@ def test_import_as() -> None:v.visit(mod)assert v.defs == set(["d"])assert v.refs == set()+ assert v.variable_data["d"] == VariableData(kind="import", module="a")def test_import_multiple() -> None:@@ -538,6 +649,8 @@ def test_import_multiple() -> None:v.visit(mod)assert v.defs == set(["a", "d"])assert v.refs == set()+ assert v.variable_data["a"] == VariableData(kind="import", module="a")+ assert v.variable_data["d"] == VariableData(kind="import", module="d")def test_from_import() -> None:@@ -547,6 +660,21 @@ def test_from_import() -> None:v.visit(mod)assert v.defs == set(["d"])assert v.refs == set()+ assert v.variable_data["d"] == VariableData(+ kind="import", module="a", import_level=0+ )+++def test_relative_from_import() -> None:+ expr = "from ..a.b.c import d"+ v = visitor.ScopedVisitor()+ mod = ast.parse(expr)+ v.visit(mod)+ assert v.defs == set(["d"])+ assert v.refs == set()+ assert v.variable_data["d"] == VariableData(+ kind="import", module="a", import_level=2+ )def test_from_import_star() -> None:@@ -558,6 +686,7 @@ def test_from_import_star() -> None:assert "`import *` is not allowed in marimo." in str(e)assert v.defs == set()assert v.refs == set()+ assert not v.variable_data@pytest.mark.skipif("sys.version_info < (3, 12)")