python / python/mypy

(🎁) Narrow dict(`TypedDict`?) entry on item assignment

Open
#13,556 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

from typing import TypedDict

class Data(TypedDict):
    a: int | None
    
d1: Data
d1['a'] = 1
d1['a'] + 1  # error: None doesn't have +

d2: Data
d2['a'] = 1
assert isinstance(d2['a'], int)
d2['a'] + 1  # no error

d3: dict[str, int | None]
d3['a'] = 1
d3['a'] + 1  # error: None doesn't have +

d4: dict[str, int | None]
d4['a'] = 1
assert isinstance(d4['a'], int)
d4['a'] + 1  # no error

Is this intentional, in that assignment doesn't narrow because a custom dict subtype could modify __setitem__ to not set/set the item to something else? If so then the narrowing should apply to TypedDicts, because they are always vanilla dicts.

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

No implementation file or test is named in the issue. Start by reproducing the four TypedDict and dict assignment examples, then trace mypy's assignment-narrowing behavior; done means the intended TypedDict result is resolved consistently and covered by a regression test.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.