Skip to content

[ty] Handle dynamic classes in string annotations - #27851

Closed
zaniebot wants to merge 1 commit into
astral-sh:mainfrom
zaniebot:agent/string-annotation-class-range
Closed

zaniebot wants to merge 1 commit into
astral-sh:mainfrom
zaniebot:agent/string-annotation-class-range

Conversation

@zaniebot

Copy link
Copy Markdown
Contributor

An invalid string annotation such as x: "type('X', (), {})[int]" can panic while reporting a diagnostic for a dynamic class. The call's NodeIndex belongs to a separately parsed annotation, but its stored scope offset is later resolved against the module AST.

Use a shared scope-relative location for dynamic-class calls. Ordinary calls retain their node offsets, while calls in string annotations retain the enclosing string's node offset and a relative source range. This restores the existing diagnostics and keeps separate calls within the same string distinct.

@astral-sh-bot astral-sh-bot Bot added the ty The ty type checker label Aug 18, 2026
@astral-sh-bot

astral-sh-bot Bot commented Aug 18, 2026

Copy link
Copy Markdown

Typing conformance results

No changes detected ✅

Current numbers
The percentage of diagnostics emitted that were expected errors held steady at 97.68%. The percentage of expected errors that received a diagnostic held steady at 93.44%. The number of fully passing files held steady at 109/136.

@astral-sh-bot

astral-sh-bot Bot commented Aug 18, 2026

Copy link
Copy Markdown

Memory usage report

Memory usage unchanged ✅

@charliermarsh charliermarsh self-assigned this Aug 19, 2026
charliermarsh added a commit that referenced this pull request Aug 19, 2026
## Summary

Previously, creating a dynamic class inside a string annotation could
panic because the call's AST node belongs to a separately parsed
annotation rather than the enclosing module:

```python
from types import new_class
from typing import Annotated


def example(
    first: "Annotated[int, type('First', (), {})]",
    second: "Annotated[int, new_class('Second', ())]",
) -> None: ...
```

Dynamic classes normally retain a scope-relative AST node index as their
identity. For calls parsed from string annotations, that index was
missing or later resolved against the wrong AST.

We now anchor those calls to the enclosing string expression and record
the call's relative source range. This preserves distinct class
identities, points diagnostics at the actual call, and handles nested
annotations without retaining absolute source positions.

Supersedes #27851.

---------

Co-authored-by: zaniebot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ty The ty type checker

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants