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: handle type params in function defs (#442)

Akshay Agrawal896e19225541
diff --git a/marimo/_ast/test_visitor.py b/marimo/_ast/test_visitor.py
index 6d8e42b057..053eb3ed09 100644
--- a/marimo/_ast/test_visitor.py
+++ b/marimo/_ast/test_visitor.py
@@ -586,3 +586,19 @@ def test_type_var_generic_class() -> None:
# T should not be among the refs or defs
assert v.defs == set(["A"])
assert v.refs == set()
+
+
[email protected]("sys.version_info < (3, 12)")
+def test_type_var_generic_function() -> None:
+ expr = cleandoc(
+ """
+ def test[U](u: U) -> U:
+ return u
+ """
+ )
+ v = visitor.ScopedVisitor()
+ mod = ast.parse(expr)
+ v.visit(mod)
+ assert v.defs == set(["test"])
+ # U should not be a ref
+ assert v.refs == set()
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 4a6e8d4dcf..0e478e0605 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -128,15 +128,27 @@ class ScopedVisitor(ast.NodeVisitor):
(Calling visit on `node`'s children is fine.) In summary:
call super().generic_visit on `node` and `visit()` on node's children.
"""
- if isinstance(
- node,
- (ast.ClassDef, ast.AsyncFunctionDef, ast.FunctionDef, ast.Lambda),
- ):
+ if isinstance(node, (ast.ClassDef, ast.Lambda)):
# These AST nodes introduce a new scope, but otherwise do not
# require special treatment.
self._push_block(is_comprehension=False)
super().generic_visit(node)
self._pop_block()
+ elif isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):
+ self._push_block(is_comprehension=False)
+ if sys.version_info >= (3, 12):
+ # We need to visit generic type parameters before arguments
+ # to make sure type parameters don't get added as refs. eg, in
+ #
+ # def foo[U](u: U) -> U: ...
+ #
+ # `U` should not be a ref
+ for child in node.type_params:
+ self.visit(child)
+ # This will revisit the type_params, but that's okay because
+ # visiting is idempotent
+ super().generic_visit(node)
+ self._pop_block()
elif isinstance(node, (ast.ListComp, ast.SetComp, ast.GeneratorExp)):
# In comprehensions, generators must be visited before elements
# because generators define local targets that elements may use.