False Positive when assigning to union type as dictionary key
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When defining a dictionary where the values are of type Union[dict, None]/Optional[dict]/dict | None and then using a conditional to confirm that the value is a dictionary before index assignment, mypy incorrectly reports that the index assignment is not valid with the following error message:
Unsupported target for indexed assignment ("dict[str, int | float] | None")
To Reproduce
https://gist.github.com/mypy-play/89bae9639af70dd72064b748098e54c5
Expected Behavior
Mypy recognizes that, due to the conditional and the assignment to an empty dict within the conditional scope, that the value is not None and is in fact an empty dictionary and does not raise a type error.
Actual Behavior
Mypy is unable to recognize that the type of the value is not None and raises a type error.
Your Environment
- Mypy version used: 1.11.1
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used: 3.12.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
Start by running the linked mypy-play reproduction with mypy 1.11.1 on Python 3.12 and confirm the reported indexed-assignment error. Trace the type-checking path for the conditional assignment to determine where the non-None dictionary type is lost; done means the reproduction no longer reports this error and related checks remain correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100