python / python/mypy

Dict literal of type `A` cannot be assigned to variable of type `A | B` (incompatible type error)

Open
#17,583 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
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

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 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.