python / python/mypy

Keys and values could be narrower for closed TypedDicts

Open
#21,700 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-typed-dict
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.