python / python/mypy

mypy shows a somewhat confusing error message for functions returning a TypeVar value

Aperta
#15,724 7 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Not sure if this should be considered a bug, or an enhancement proposal...

I had some code looking like this:

CallbackResult = TypeVar("CallbackResult")
VisitCallback = Callable[[str], Optional[CallbackResult]]

def visititems(self, func: VisitCallback) -> CallbackResult:
    return func("test")

Actual Behavior

mypy says about this code:

error: A function returning TypeVar should receive at least one argument containing the same TypeVar  [type-var]

Expected Behavior

First, I was confused, and thought that mypy is not able to infer that CallbackResult is hidden in the function input as the return value of VisitCallback. Actually I was initially going to open an issue because of that.

Then I noticed that in a sense, mypy is correct - because I spotted that VisitCallback returns Optional[CallbackResult], while the visititems function returns a CallbackResult.

Once I fixed that, the error went away. But in this case, mypy did not really "pinpoint" the problem as well as I feel it could.

Not sure how deeply mypy plays out the type algebra to figure out what types are constructible in a context, but I feel like this specific case could be a rather "common" one (forgetting the Optional), so maybe this can be catched with a better error message.

Maybe something of the form "the function returns typevar value X, but based on its inputs can only construct Y[X, ...]" could be possible? So that it would cover Optional, Union and other simple cases like List, etc.

Your Environment

  • Mypy version used: 1.1.1

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 di TypeVar dell'issue ed esaminando come mypy segnala l'errore di type-var quando Optional[CallbackResult] viene restituito come CallbackResult. Il lavoro è completato quando viene prodotto un diagnostico più chiaro che spieghi la discrepanza e copra wrapper semplici come Optional, Union o List.

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

Valutazione

Stack tecnologico
python
Ambito
compilers, devtools
Tipo di issue
Funzionalità
Difficoltà
4/5
Tempo stimato
3-5 giorni
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.