Skip to content

Assignment to field of typed dict doesn't change its (field) type #19369

Open
@RomanValov

Description

@RomanValov

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions