python / python/mypy

Keys and values could be narrower for closed TypedDicts

Aperta
#21,700 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature topic-typed-dict
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

I was very excited to try out mypy 2.2 with the initial support for the TypedDict closed keyword.
But in our code base, where we often iterate over TypedDicts, it did not help much because the keys and values are still inferred as str and object, respectively.

from typing_extensions import TypedDict, reveal_type


class Closed(TypedDict, closed=True, total=False):
    a: int
    b: str

c = Closed(a=1, b='a')
reveal_type(c.items())

for key, val in c.items():
    c[key]
$ mypy --pretty test.py
test.py:9: note: Revealed type is "_collections_abc.dict_items[str, object]"
test.py:12: error: TypedDict key must be a string literal; expected one of ("a", "b")  [literal-required]
        c[key]
          ^~~
Found 1 error in 1 file (checked 1 source file)

ty narrows both keys and values here

$ ty check test.py
ty check test.py 
info[revealed-type]: Revealed type
 --> test.py:9:13
  |
9 | reveal_type(c.items())
  |             ^^^^^^^^^^ `dict_items[Literal["a", "b"], int | str]`
  |

Found 1 diagnostic

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 riproducendo l’esempio test.py dell’issue con mypy --pretty, concentrandoti su TypedDict.items() e sul successivo accesso c[key]. Traccia il percorso di controllo dei tipi TypedDict responsabile di questi tipi inferiti; il lavoro è completato quando l’iterazione su un TypedDict chiuso rivela un’unione letterale delle chiavi e i corrispondenti tipi di valore, e l’accesso tramite indice con la chiave iterata viene accettato.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.