python / python/mypy

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

Aperta
#17,583 4 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo mypy sull’esempio minimo in main.py, usando la riproduzione collegata di mypy-play per confermare il comportamento. Traccia la gestione dei letterali dict assegnati a unioni di tipi dict e aggiungi una copertura che mostri che entrambe le assegnazioni passano senza errori.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.