From 6030d05b2861d6e2695229528c64248673112eea Mon Sep 17 00:00:00 2001 From: Craig Barratt <19445341+craigbarratt@users.noreply.github.com> Date: Sat, 5 Dec 2026 13:50:21 -0800 Subject: [PATCH] Don't evaluate a function's local variable annotations, as in Python (#796) Python never evaluates or stores the annotation of a local variable in a function, so `y: Any[int] = None` inside a function runs without error. Pyscript evaluated it and failed with TypeError. Module and class annotations are unchanged. Co-Authored-By: Claude Opus 5.5 --- custom_components/pyscript/eval.py | 8 ++----- tests/test_unit_eval.py | 37 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index 363f570..362fe0c 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -1762,13 +1762,9 @@ async def ast_augassign(self, arg): async def ast_annassign(self, arg): """Execute type hint assignment statement and track __annotations__.""" - if isinstance(arg.target, ast.Name): + # as in Python, the annotation of a function's local variable is never evaluated or stored + if isinstance(arg.target, ast.Name) and not self.in_local_scope(): annotations = self.sym_table.setdefault("__annotations__", {}) - if isinstance(annotations, EvalLocalVar): - # a function's own __annotations__ variable - if not annotations.is_defined(): - annotations.set({}) - annotations = annotations.get() if arg.annotation: try: annotations[arg.target.id] = await self.aeval(arg.annotation) diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index c213082..60b0e45 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -6854,6 +6854,43 @@ def f(): x: int = 1 return x result = f() +""", + """ +def f(): + __annotations__ = {} + x: int = 1 + return x, __annotations__ +result = f() +""", + # a local variable's annotation is never evaluated (#796) + """ +from typing import Any +def f(): + y: Any[int] = None + z: undefined_name = 2 + return y, z +result = f() +""", + """ +calls = [] +def note(name): + calls.append(name) + return int +def f(): + x: note("local") = 1 + class C: + y: note("class") = 2 + return x, C.y, C.__annotations__ +result = f(), calls +""", + """ +def f(): + x: int + try: + return x + except UnboundLocalError as exc: + return type(exc).__name__ +result = f() """, """ def f():