python / python/mypy

Inconsistent handling of unsolved TypeVars

Aperta
#10,241 1 commento 3 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-type-variables
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

PEP 484 doesn't provide much clarity about the situation where a TypeVar is provided with no value in a generic function call, so I'm not sure if there is a "correct" behavior. However, I'd expect that the behavior would at least be consistent for a type checker.

from typing import Optional, TypeVar

T1 = TypeVar("T1")
def func1(suffix: Optional[T1] = ...) -> T1:
    ...

T2 = TypeVar("T2", bound=str)
def func2(suffix: Optional[T2] = ...) -> T2:
    ...

T3 = TypeVar("T3", str, bytes)
def func3(suffix: Optional[T3] = ...) -> T3:
    ...

T4 = TypeVar("T4", bytes, str)
def func4(suffix: Optional[T4] = ...) -> T4:
    ...

reveal_type(func1()) # <nothing>
reveal_type(func2()) # <nothing>
reveal_type(func3()) # str
reveal_type(func4()) # bytes

Note that mypy's results depend on whether the TypeVar is bound or constrained. If it is constrained, mypy appears to (arbitrarily?) choose the first constrained type.

Note that this situation arises in some common situations like the following:

from tempfile import mkstemp
_, temp_path = mkstemp()
reveal_type(temp_path) # str?

Like I said, I'm not sure what the "correct" or intended behavior is in this case, but the current behavior strikes me as inconsistent.

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

Non sono indicati file o test. Inizia riproducendo i quattro esempi di funzioni generiche e il caso mkstemp(), quindi confronta i tipi inferiti per TypeVars non vincolati, vincolati e con vincoli. Il lavoro è completato quando è stato concordato un comportamento coerente, seguito dall’implementazione e dalla copertura delle regressioni.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.