[ty] Use declared attribute types as type context (#21143)

## Summary

For example:
```py
class X:
    x: list[int | str]

def _(x: X):
    x.x = [1]
```

Resolves https://github.com/astral-sh/ty/issues/1375.
This commit is contained in:
Ibraheem Ahmed
2025-10-31 11:48:28 -04:00
committed by GitHub
parent b93d8f2b9f
commit bb40c34361
3 changed files with 304 additions and 107 deletions

View File

@@ -281,46 +281,3 @@ def _(flag: bool):
# we currently consider `TypedDict` instances to be subtypes of `dict`
f({"y": 1})
```
Diagnostics unrelated to the type-context are only reported once:
`expression.py`:
```py
def f[T](x: T) -> list[T]:
return [x]
def a(x: list[bool], y: list[bool]): ...
def b(x: list[int], y: list[int]): ...
def c(x: list[int], y: list[int]): ...
def _(x: int):
if x == 0:
y = a
elif x == 1:
y = b
else:
y = c
if x == 0:
z = True
y(f(True), [True])
# error: [possibly-unresolved-reference] "Name `z` used when possibly not defined"
y(f(True), [z])
```
`standalone_expression.py`:
```py
def f(_: str): ...
def g(_: str): ...
def _(a: object, b: object, flag: bool):
if flag:
x = f
else:
x = g
# error: [unsupported-operator] "Operator `>` is not supported for types `object` and `object`"
x(f"{'a' if a > b else 'b'}")
```