[ty] Infer more precise types for collection literals (#20360)

## Summary

Part of https://github.com/astral-sh/ty/issues/168. Infer more precise types for collection literals (currently, only `list` and `set`). For example,

```py
x = [1, 2, 3] # revealed: list[Unknown | int]
y: list[int] = [1, 2, 3] # revealed: list[int]
```

This could easily be extended to `dict` literals, but I am intentionally limiting scope for now.
This commit is contained in:
Ibraheem Ahmed
2025-09-17 18:51:50 -04:00
committed by GitHub
parent bfb0902446
commit e84d523bcf
16 changed files with 341 additions and 78 deletions

View File

@@ -79,6 +79,78 @@ b: tuple[int] = ("foo",)
c: tuple[str | int, str] = ([], "foo")
```
## Collection literal annotations are understood
```toml
[environment]
python-version = "3.12"
```
```py
import typing
a: list[int] = [1, 2, 3]
reveal_type(a) # revealed: list[int]
b: list[int | str] = [1, 2, 3]
reveal_type(b) # revealed: list[int | str]
c: typing.List[int] = [1, 2, 3]
reveal_type(c) # revealed: list[int]
d: list[typing.Any] = []
reveal_type(d) # revealed: list[Any]
e: set[int] = {1, 2, 3}
reveal_type(e) # revealed: set[int]
f: set[int | str] = {1, 2, 3}
reveal_type(f) # revealed: set[int | str]
g: typing.Set[int] = {1, 2, 3}
reveal_type(g) # revealed: set[int]
h: list[list[int]] = [[], [42]]
reveal_type(h) # revealed: list[list[int]]
i: list[typing.Any] = [1, 2, "3", ([4],)]
reveal_type(i) # revealed: list[Any | int | str | tuple[list[Unknown | int]]]
j: list[tuple[str | int, ...]] = [(1, 2), ("foo", "bar"), ()]
reveal_type(j) # revealed: list[tuple[str | int, ...]]
k: list[tuple[list[int], ...]] = [([],), ([1, 2], [3, 4]), ([5], [6], [7])]
reveal_type(k) # revealed: list[tuple[list[int], ...]]
l: tuple[list[int], *tuple[list[typing.Any], ...], list[str]] = ([1, 2, 3], [4, 5, 6], [7, 8, 9], ["10", "11", "12"])
reveal_type(l) # revealed: tuple[list[int], list[Any | int], list[Any | int], list[str]]
type IntList = list[int]
m: IntList = [1, 2, 3]
reveal_type(m) # revealed: list[int]
# TODO: this should type-check and avoid literal promotion
# error: [invalid-assignment] "Object of type `list[int]` is not assignable to `list[Literal[1, 2, 3]]`"
n: list[typing.Literal[1, 2, 3]] = [1, 2, 3]
reveal_type(n) # revealed: list[Literal[1, 2, 3]]
# TODO: this should type-check and avoid literal promotion
# error: [invalid-assignment] "Object of type `list[str]` is not assignable to `list[LiteralString]`"
o: list[typing.LiteralString] = ["a", "b", "c"]
reveal_type(o) # revealed: list[LiteralString]
```
## Incorrect collection literal assignments are complained aobut
```py
# error: [invalid-assignment] "Object of type `list[int]` is not assignable to `list[str]`"
a: list[str] = [1, 2, 3]
# error: [invalid-assignment] "Object of type `set[int | str]` is not assignable to `set[int]`"
b: set[int] = {1, 2, "3"}
```
## PEP-604 annotations are supported
```py