Assignment to field of typed dict doesn't change its (field) type
Open
Nobody has claimed this yet.
bug
topic-type-narrowing
topic-typed-dict
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Please check the example and its output
To Reproduce
from typing import TypedDict
class MyDict(TypedDict, total=False):
name: str | None
if __name__ == '__main__':
d1: MyDict = {'name': 'Bob'}
d0: MyDict = {}
d0['name'] = d0.get('name')
reveal_type(d0['name'])
if d0['name'] is None:
reveal_type(d0['name'])
d0['name'] = 'Alice'
reveal_type(d0['name'])
reveal_type(d0['name'])
d0['name'][:]
Observed Output
dict.py:14: note: Revealed type is "Union[builtins.str, None]"
dict.py:16: note: Revealed type is "None"
dict.py:18: note: Revealed type is "None"
dict.py:20: note: Revealed type is "Union[builtins.str, None]"
dict.py:21: error: Value of type "str | None" is not indexable [index]
Found 1 error in 1 file (checked 1 source file)
Expected Behavior
The d0 on last line of the example is inferred as str
Actual Behavior
The d0 on last line of the example is inferred as str | None
Your Environment
python: 3.12.3
mypy: 1.16.0
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
Run the supplied Python reproducer with mypy 1.16.0 and compare each reveal_type result with the expected behavior. Trace how TypedDict assignment and narrowing are handled, then add coverage for this case; done means the final access is inferred as str without an error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100