python / python/typing

Positional arguments to TypedDict constructor

Aperta
#2,161 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

topic: typing spec
Lingua principale
Python
Stelle
1.8k
Fork
302
Merge medio
23h
PR unite (30g)
8

Descrizione

The spec says "The constructor takes only keyword arguments, corresponding to the items of the TypedDict." This derives from wording in PEP 589 "It can be used as a callable object with keyword arguments corresponding to the TypedDict items. Non-keyword arguments are not allowed."

But at runtime, the TypedDict constructor also takes positional arguments. This works:

from typing import TypedDict
class TD1(TypedDict):
    a: int
class TD2(TD1):
    b: str

def f(x: TD2) -> TD1:
    return TD1(x)

Pyright allows this program; mypy does not and reports Expected keyword arguments, {...}, or dict(...) in TypedDict constructor.

The spec should say whether or not this should be allowed. (My opinion: it should be allowed, since it works at runtime and doesn't appear to break any type safety rule.)

At runtime, even more is allowed; the TypedDict constructor actually allows whatever dict() allows. So you could do TD1([("a", 1)]), or TD1(TD2, a=3). Pyright allows some but not all of that. I'm inclined to prohibit anything other than calls with keyword arguments and calls with a single positional argument of TypedDict type; anything else is rarely useful and prone to unsound behavior.

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

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 specifica collegata del costruttore di TypedDict e con la sezione corrispondente di PEP 589, quindi confronta le regole documentate con gli esempi a runtime e con i diversi comportamenti di mypy e Pyright descritti qui. Il lavoro è concluso quando è stata presa una decisione sugli argomenti posizionali consentiti e la specifica è stata aggiornata con una formulazione normativa chiara.

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

Valutazione

Stack tecnologico
python
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Tranquilla
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.