python / python/typing

TypeVar substitution in get_type_hints

Aperta
#776 10 commenti 9 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

When it comes to generic classes, type annotations retrieved with get_type_hints are not really easy to use, as in the following example:

from typing import Generic, TypeVar, get_type_hints

T = TypeVar("T")
class A(Generic[T]):
    a: T

U = TypeVar("U")
class B(A[U]):
    b: U

assert get_type_hints(B) == {"a": T, "b": U}

It could be useful to add a TypeVar substitution to get_type_hints, for example with an additional substitute_type_vars parameter (with a False default)
By the way, get_type_hints could also allow to pass generic alias in order to substitute directly TypeVars with their related argument.

It would give for the example above:

assert get_type_hints(B, substitute_type_vars=True) == {"a": U, "b": U}  # typevars are consistent
assert get_type_hints(B[T], substitute_type_vars=True) == {"a": T, "b": T}
assert get_type_hints(B[int], substitute_type_vars=True) == {"a": int, "b": int}  # ready to use

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 l’API get_type_hints e gli esempi di generic-class nell’issue, quindi esamina come sono attualmente rappresentati i generic aliases e le relazioni di TypeVar. Il lavoro è completo quando sarà stato definito e implementato il comportamento di sostituzione proposto, incluso il parametro disabilitato per impostazione predefinita e gli input degli alias, con test che coprano B, B[T] e B[int].

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
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.