Dict unpacking fails when used for building TypedDict with required keys
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When dict unpacking is used to dynamically add optional keys to a TypedDict, mypy raises a typeddict-item error.
As dict unpacking is used to fill some keys from the TypedDict, my understanding is that mypy could validate the unpacked dictionaries considering all keys as NotRequired, and only the final TypedDict respecting its formal definition.
To Reproduce
Gist: https://mypy-play.net/?mypy=latest&python=3.13&gist=b3377281f7f5a6f83dd9962d60302827
from typing import NotRequired, TypedDict
class Project(TypedDict):
name: str
version: NotRequired[str]
def build_project(name: str, version: str | None = None) -> Project:
return {
"name": name,
**({"version": version} if version is not None else {})
}
Actual Behavior
$ mypy .
main.py:12: error: Missing key "name" for TypedDict "Project" [typeddict-item]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used:
1.17.0 - Mypy command-line flags: N/A
- Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used:
3.13.5
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 with the linked mypy-play reproduction and run the shown example under Python 3.13. Read the TypedDict and dict-unpacking handling reached by this case, then add a regression test for the reported error. Done means the example accepts the required "name" key and optional unpacked "version" without a typeddict-item error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100