False positive `[operator]` on union of dicts with heterogeneous value types
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
If I take the union of two dicts with different value types, I cannot assign the result to a variable that is annotated with the resulting type. Doing so causes an error. Assigning to an non-annotated variable does not cause an error, which seems like the correct behavior.
Do I really need the annotation on d5 below? No. But I have a non-toy example of this in a code base where d5 is a type annotated attribute on an object, which results in the same error.
d1: dict[str, str] = {}
d2: dict[str, str | None] = {}
d3 = d1 | d2
reveal_type(d3) # builtins.dict[builtins.str, Union[builtins.str, None]], aka dict[str, str | None]
# This is fine
d4: dict[str, str | None] = d3 # aka d1 | d2
# This isn't?
d5: dict[str, str | None] = d1 | d2
To Reproduce
Expected Behavior
I expect d5: dict[str, str | None] = d1 | d2 to be legal.
Actual Behavior
error: Unsupported operand types for | ("dict[str, str]" and "dict[str, str | None]") [operator].
Your Environment
- Mypy version used: 1.13.0
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - 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 with the minimal reproduction in the issue or its linked mypy-play example, using the reported Python 3.12 and mypy 1.13.0 context. Compare the annotated direct union with the intermediate variable case, then verify that the direct assignment no longer emits the [operator] error while the revealed type remains dict[str, str | None].
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100