[ty] Add precise iteration and unpacking inference for string literals and bytes literals (#20023)

## Summary

Previously we held off from doing this because we weren't sure that it
was worth the added complexity cost. But our code has changed in the
months since we made that initial decision, and I think the structure of
the code is such that it no longer really leads to much added complexity
to add precise inference when unpacking a string literal or a bytes
literal.

The improved inference we gain from this has real benefits to users (see
the mypy_primer report), and this PR doesn't appear to have a
performance impact.

## Test plan

mdtests
This commit is contained in:
Alex Waygood 2025-08-22 19:33:08 +01:00 committed by GitHub
parent 796819e7a0
commit bc6ea68733
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 203 additions and 43 deletions

View file

@ -755,6 +755,18 @@ def f(never: Never):
reveal_type(x) # revealed: Unknown
```
## Iterating over literals
```py
from typing import Literal
for char in "abcde":
reveal_type(char) # revealed: Literal["a", "b", "c", "d", "e"]
for char in b"abcde":
reveal_type(char) # revealed: Literal[97, 98, 99, 100, 101]
```
## A class literal is iterable if it inherits from `Any`
A class literal can be iterated over if it has `Any` or `Unknown` in its MRO, since the