python / python/mypy

False positive `[operator]` on union of dicts with heterogeneous value types

Open
#18,236 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-context
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

See: https://mypy-play.net/?mypy=master&python=3.13&flags=show-error-codes&gist=2643cb3ff1ea956a1c4ed0869140d46d

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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.