python / python/mypy

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

Aperta
#18,236 3 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

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

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 con la riproduzione minima nell’issue o nell’esempio mypy-play collegato, usando il contesto indicato di Python 3.12 e mypy 1.13.0. Confronta l’unione diretta annotata con il caso della variabile intermedia, quindi verifica che l’assegnazione diretta non produca più l’errore [operator], mentre il tipo rivelato rimanga dict[str, str | None].

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

Valutazione

Stack tecnologico
python
Ambito
compilers
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.