python / python/mypy

Set and Dict generalizing the type unnecessarily

Aperta
#17,238 0 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

See these two example functions:

def f(items: list[str] | list[int]) -> None:
    items_as_set: set[str] | set[int] = set(items)

def g(key_to_count: dict[str, float] | dict[int, float]) -> None:
    key_to_count_2: dict[str, float] | dict[int, float] = {k: v for k, v in key_to_count.items()}

Mypy 1.10.0 complains about the assignment in each of them:

test_mypy_dict.py:2: error: Incompatible types in assignment (expression has type "set[object]", variable has type "set[str] | set[int]")  [assignment]
test_mypy_dict.py:5: error: Incompatible types in assignment (expression has type "dict[str | int, float]", variable has type "dict[str, float] | dict[int, float]")  [assignment]

To Reproduce

Playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=83bde5f3f11470e94b6a680158649641

Expected Behavior

The set() or dict() operation applied on a variable that is either a list[str] | list[int] is always either a set[str] or set[int]. The same applies to function g using a dict. Thus the functions should not raise a mypy error.

Workarounds

I tried two workarounds:

  • Using a mixed type of list[str | int]. However, I get the type list[str] | list[int] by an external function, thus this is not compatible.
  • Using a generic. This is not working either.

See the playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=264490179628a0a214a2e5bd947b8ccf
image

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 le due riproduzioni Python dell’issue, inclusi gli esempi mypy-play collegati, e confronta i tipi inferiti e gli errori di assegnazione per set() e la dict comprehension. Traccia il percorso del controllo dei tipi per queste espressioni di costruttore e comprehension; il lavoro è completato quando entrambe le funzioni vengono verificate senza errori, preservando l’unione di tipi di contenitore omogenei.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.