Dict literal of type `A` cannot be assigned to variable of type `A | B` (incompatible type error)
Personne n'a encore pris cette issue.
- Langage dominant
- Python
- Étoiles
- 20.6k
- Forks
- 3.3k
- Métriques de merge des PR
- Métriques de PR en attente
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
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez par exécuter mypy sur l’exemple minimal dans main.py, en utilisant la reproduction mypy-play liée pour confirmer le comportement. Suivez le traitement des littéraux dict affectés à des unions de types dict, et ajoutez une couverture montrant que les deux affectations passent sans erreur.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- python
- Domaine
- tooling
- Type d'issue
- Bug
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 45/100