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(ast): handle PEP 695 TypeAlias in DeprivateVisitor (#10227)
Bartokc55f69b43d0a
diff --git a/marimo/_ast/transformers.py b/marimo/_ast/transformers.pyindex 59caed95c4..d61085ee0f 100644--- a/marimo/_ast/transformers.py+++ b/marimo/_ast/transformers.py@@ -458,9 +458,19 @@ class DeprivateVisitor(ast.NodeTransformer):node.id = unmangle_local(node.id).namereturn node+ def visit_TypeAlias(self, node: ast.TypeAlias) -> ast.TypeAlias:+ # PEP 695 `type Alias = ...` stores the alias as an ast.Name on+ # `node.name` (not a bare str). Only unmangle the identifier.+ if isinstance(node.name, ast.Name):+ node.name.id = unmangle_local(node.name.id).name+ return cast(ast.TypeAlias, self.generic_visit(node))+def generic_visit(self, node: ast.AST) -> ast.AST:- if hasattr(node, "name") and node.name:- node.name = unmangle_local(node.name).name+ # Many statement nodes expose `name: str` (FunctionDef, ClassDef,+ # ExceptHandler, …). NB. Not always a string. e.g. TypeAlias.name is an+ # ast.Name+ if hasattr(node, "name") and isinstance(node.name or None, str):+ node.name = unmangle_local(node.name).name # type: ignore[attr-defined]return super().generic_visit(node)diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex 370b9eae41..8dd98bce58 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -10,7 +10,7 @@ import sysimport typesfrom typing import TYPE_CHECKING, Any, NamedTuple-from marimo._ast.transformers import DeprivateVisitor, get_hashable_ast+from marimo._ast.transformers import DeprivateVisitorfrom marimo._ast.variables import (get_cell_from_local,if_local_then_mangle,@@ -143,14 +143,6 @@ def hash_cell_impl(cell: CellImpl, hash_type: str = DEFAULT_HASH) -> bytes:)-def hash_function(- fn: Callable[..., Any], hash_type: str = DEFAULT_HASH-) -> bytes:- return hash_raw_module(- DeprivateVisitor().visit(get_hashable_ast(fn)), hash_type- )--def hash_cell_group(cell_ids: set[CellId_t],graph: GraphTopology,diff --git a/tests/_ast/test_transformers.py b/tests/_ast/test_transformers.pyindex 764430cf53..41159b5019 100644--- a/tests/_ast/test_transformers.py+++ b/tests/_ast/test_transformers.py@@ -1,6 +1,7 @@from __future__ import annotationsimport ast+import sysimport pytest@@ -362,6 +363,35 @@ def test_deprivate_visitor() -> None:assert "_cell_123_private_var" not in code_result+ sys.version_info < (3, 12),+ reason="PEP 695 `type` alias syntax requires Python 3.12+",+)+def test_deprivate_visitor_type_alias() -> None:+ """PEP 695 TypeAlias.name is ast.Name — must not call str methods."""+ code = "type Mode = str\nclass C:\n x: Mode = 'a'\n"+ tree = ast.parse(code)+ result = DeprivateVisitor().visit(tree)+ code_result = ast.unparse(result)+ assert "type Mode" in code_result+ assert "class C" in code_result+++ sys.version_info < (3, 12),+ reason="PEP 695 `type` alias syntax requires Python 3.12+",+)+def test_deprivate_visitor_mangled_type_alias() -> None:+ """Mangled identifiers inside type aliases are deprivated."""+ code = "type _cell_ab_Mode = _cell_ab_int_name"+ tree = ast.parse(code)+ # Hand-mangle Name target if the parser left a plain id+ result = DeprivateVisitor().visit(tree)+ code_result = ast.unparse(result)+ assert "_cell_ab" not in code_result+ assert "_Mode" in code_result or "Mode" in code_result++def test_remove_returns() -> None:"""Test the RemoveReturns transformer."""code = """diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex 8c9db07faa..853b69ea51 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -3479,6 +3479,63 @@ class TestAsyncCacheDecorator:"First execution should be a miss, deduplication doesn't count as hits")+ @pytest.mark.skipif(+ sys.version_info < (3, 12),+ reason="PEP 695 `type` alias syntax requires Python 3.12+",+ )+ async def test_cache_dataclass_with_type_alias(+ self, any_kernel: Kernel+ ) -> None:+ """@mo.cache + dataclass field using PEP 695 type alias (#10192).++ Keep the `type` statement inside executed cell source so the test+ module itself parses on Python 3.10/3.11 (ruff target-version).+ """+ k = any_kernel+ await k.run(+ [+ ExecuteCellCommand(+ cell_id="setup",+ code=textwrap.dedent(+ """+ import marimo as mo+ from dataclasses import dataclass+ from typing import Literal++ type Mode = Literal["auto", "manual"]+ """+ ),+ ),+ ExecuteCellCommand(+ cell_id="0",+ code=textwrap.dedent(+ """+ @dataclass+ class Config:+ mode: Mode = "auto"+ """+ ),+ ),+ ExecuteCellCommand(+ cell_id="1",+ code=textwrap.dedent(+ """+ @mo.cache+ def build(mode: Mode = "auto") -> Config:+ return Config(mode=mode)++ cfg = build()+ cfg2 = build()+ """+ ),+ ),+ ]+ )+ assert k.errors == {}+ assert not k.stderr.messages, k.stderr+ assert k.globals["cfg"].mode == "auto"+ assert k.globals["build"].hits == 1+async def test_async_cache_stale_task_different_loop(self, k: Kernel, exec_req: ExecReqProvider) -> None: