python / python/typing

(🎁) Support type variables in the bounds of other type variables

Aperta
#1,226 7 commenti 12 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

from typing import _T as T, TypeVar

L = TypeVar("L", bound=list[T])  # error: Type variable "typing._T" is unbound

def foo(l: L) -> L | T:  # error: A function returning TypeVar should receive at least one argument containing the same Typevar
    res = l[0]
    if res:
        return res
    return l

a: list[int] | list[str]

reveal_type(foo)  # "def [L <: list[T?], T] (l: L) -> L | T"
reveal_type(foo(a))  # list[int] | list[str]

Expected:

reveal_type(foo)  # "def [T, L <: list[T]] (l: L) -> L | T"
reveal_type(foo(a))  # list[int] | list[str] | int | str

Mypy should understand that T should be bound to foo from L

This is identical to generic TypeAliases:

L: TypeAlias = list[T]
a: L[int]

Here T is unbound, yet it's a valid and semantically sound expression.

Typescript example

The same idea could be represented in TypeScript as:

declare function foo<T, L extends T[]>(l: L): L | T

declare let a: number[] | string[]

let b = foo(a)

Although TS fails to infer the correct type here. (it infers as unknown)

basedmypy

This is partially supported in basedmypy

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 gli esempi di TypeVar e TypeAlias generico nell’issue, quindi confronta la gestione attuale dei bounds e dei tipi inferiti. Il lavoro è completato quando gli output reveal_type mostrati trattano T come vincolato tramite L e producono l’unione prevista per foo(a).

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
28/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.