python / python/mypy

Faulty type narrowing with value restrictions

Aperta
#13,083 0 commenti 0 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

Bug Report

When passing an empty list directly into a value restricted generic function, the inferred return type can end up being too narrow.

To Reproduce

from typing import TypeVar


TV = TypeVar("TV", str, int)


def foo(x: list[TV]) -> list[TV]:
    return x
    

# Should be: builtins.list[builtins.str] | builtins.list[builtins.int]
reveal_type(foo([]))  # "builtins.list[builtins.str]"

https://mypy-play.net/?mypy=latest&python=3.10&flags=strict&gist=129ba2fed0c6ba1a861149f944db3420

Expected Behavior

I would expect the revealed type to either be builtins.list[builtins.str] | builtins.list[builtins.int].

Alternatively, having this result in an error of some sort would be fine. As a reference, when assigning the empty list first, it becomes a list[Any] instead of a list[<nothing>]. This results in the revealed type being list[Any], but also an error along the lines of Need type annotation for "l" (hint: "l: List[<type>] = ...").

Actual Behavior

The revealed type was builtins.list[builtins.str]

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 con il riproduttore mypy-play collegato e traccia la gestione degli argomenti di liste vuote durante l'inferenza di un TypeVar con valori vincolati. Confronta il tipo inferito con l'unione prevista e con il comportamento diagnostico accettabile descritto nell'issue. Il lavoro è completato quando l'esempio non viene più ristretto erroneamente a list[str].

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.