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: allow generics on top level definitions (#7417)

Dylan Madisettic4c846ec1efc
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 3659b87df5..4ec0d39221 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -561,6 +561,14 @@ class ScopedVisitor(ast.NodeVisitor):
# the variable `foo` needs to be aware that it may require the ref `x`
# during execution.
self.ref_stack[-1].update(refs)
+
+ # Prune type_params
+ if sys.version_info >= (3, 12):
+ type_params = getattr(node, "type_params", [])
+ generics = {param.name for param in type_params}
+ refs -= generics
+ unbounded_refs -= generics
+
# Return both sets of refs
return refs, unbounded_refs
diff --git a/tests/_ast/test_toplevel.py b/tests/_ast/test_toplevel.py
index 3b65ebb981..2dc2ab0ced 100644
--- a/tests/_ast/test_toplevel.py
+++ b/tests/_ast/test_toplevel.py
@@ -2,6 +2,10 @@
from __future__ import annotations
+import sys
+
+import pytest
+
from marimo._ast import toplevel
from marimo._ast.app import App, InternalApp
from marimo._ast.toplevel import (
@@ -568,6 +572,23 @@ class TestTopLevelClasses:
TopLevelType.TOPLEVEL,
] == [s.type for s in extraction], [s.hint for s in extraction]
+ @staticmethod
+ @pytest.mark.skipif(
+ sys.version_info < (3, 12),
+ reason="Requires Python 3.12+ for generic type parameter syntax",
+ )
+ def test_class_generic_type_parameter() -> None:
+ from marimo._ast.compiler import compile_cell
+
+ code = """\
+class GenericTypeParameter[T]:
+ def __init__(self, value: T):
+ self.value = value
+"""
+ cell = compile_cell(code, cell_id="test")
+ status = TopLevelStatus.from_cell(cell, BUILTINS)
+ assert status.type == TopLevelType.TOPLEVEL, status.hint
+
class TestTopLevelHook:
@staticmethod