Skip to content

Don't evaluate a function's local variable annotations, as in Python (#796) - #951

Open
craigbarratt wants to merge 1 commit into
masterfrom
local-annotations-unevaluated
Open

craigbarratt wants to merge 1 commit into
masterfrom
local-annotations-unevaluated

Conversation

@craigbarratt

Copy link
Copy Markdown
Member

Fixes #796.

Python never evaluates or stores the annotation of a local variable in a function. Pyscript evaluated it each time the assignment ran, so y: Any[int] = None inside a function raised TypeError: type 'Any' is not subscriptable, and an undefined name in the annotation was kept as a string in a local __annotations__.

ast_annassign now skips the annotation in a function's local scope and only assigns the value. Module and class annotations are unchanged, including a class body inside a function. The branch that kept a function's own __annotations__ variable is no longer needed.

Tests: new cases in FUNCTION_LOCALS_TESTS, compared with CPython and also run inside an inner function:

  • the Errors with type annotation handling in 1.7.0 #796 example and an undefined name in a local annotation;
  • a local annotation with a side effect isn't evaluated, while a class body's annotation in the same function is;
  • x: int with no value still makes x an unbound local;
  • a function's own __annotations__ isn't updated by a local annotation.

The new tests fail on master. All 307 tests pass, and ruff, pylint and mypy are clean.

🤖 Generated with Claude Code

…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 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Errors with type annotation handling in 1.7.0

1 participant