Dict literal of type `A` cannot be assigned to variable of type `A | B` (incompatible type error)
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Mypy fails with unions of a union of dict types with literal keys: a dict literal which can be assigned to a variable of type A cannot be assigned to a variable of type A | B.
To Reproduce
Gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=4564762bf0284f05695be7fc30c79020
from typing import Literal
A = dict[Literal["foo"], str]
B = dict[Literal["bar"], int]
a: A = {"foo": "s"} # works
b: B = {"bar": 5} # works
T = A | B
t1: T = {"foo": "s"} # error
t2: T = {"bar": 5} # error
Expected Behavior
It should work without errors.
Actual Behavior
main.py:10: error: Incompatible types in assignment (expression has type "dict[str, str]", variable has type "dict[Literal['foo'], str] | dict[Literal['bar'], int]") [assignment]
main.py:11: error: Incompatible types in assignment (expression has type "dict[str, int]", variable has type "dict[Literal['foo'], str] | dict[Literal['bar'], int]") [assignment]
Your Environment
- Mypy version used: 1.11.0
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.12
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 mypy on the minimal example in main.py, using the linked mypy-play reproduction to confirm the behavior. Trace the handling of dict literals assigned to unions of dict types, and add coverage showing that both assignments pass without errors.
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