Keys and values could be narrower for closed TypedDicts
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
I was very excited to try out mypy 2.2 with the initial support for the TypedDict closed keyword.
But in our code base, where we often iterate over TypedDicts, it did not help much because the keys and values are still inferred as str and object, respectively.
from typing_extensions import TypedDict, reveal_type
class Closed(TypedDict, closed=True, total=False):
a: int
b: str
c = Closed(a=1, b='a')
reveal_type(c.items())
for key, val in c.items():
c[key]
$ mypy --pretty test.py
test.py:9: note: Revealed type is "_collections_abc.dict_items[str, object]"
test.py:12: error: TypedDict key must be a string literal; expected one of ("a", "b") [literal-required]
c[key]
^~~
Found 1 error in 1 file (checked 1 source file)
ty narrows both keys and values here
$ ty check test.py
ty check test.py
info[revealed-type]: Revealed type
--> test.py:9:13
|
9 | reveal_type(c.items())
| ^^^^^^^^^^ `dict_items[Literal["a", "b"], int | str]`
|
Found 1 diagnostic
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the issue's test.py example with mypy --pretty, focusing on TypedDict.items() and the subsequent c[key] access. Trace the TypedDict type-checking path responsible for these inferred types; done means closed TypedDict iteration reveals a literal union of keys and corresponding value types, and indexing with the iterated key is accepted.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100