`filter` does not narrow `TypeVar` used in `TypeGuard` signature
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug Report
Using filter with a TypeGuard, the TypeVar used in the TypeGuard signature is not properly narrowed.
To Reproduce
# tmp.py
from typing import Iterator, Optional, TypeVar
from typing_extensions import TypeGuard
T = TypeVar("T")
def is_not_none(x: Optional[T]) -> TypeGuard[T]:
return x is not None
maybe_ints: list[Optional[int]] = [1, None, 2]
ints: Iterator[int] = filter(is_not_none, maybe_ints)
$ mypy tmp.py
tmp.py:14: error: Argument 1 to "filter" has incompatible type "Callable[[Optional[T]], TypeGuard[T]]"; expected "Callable[[Optional[int]], TypeGuard[int]]"
Found 1 error in 1 file (checked 1 source file)
Expected Behavior
I wouldn't expect any error. Since the second argument to filter is typed as list[Optional[int]], mypy should narrow the TypeVar T appropriately.
Your Environment
- Mypy version used:
mypy 0.950 - Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.10
This may be related to https://github.com/python/mypy/issues/12682. I decided to open a new ticket instead of commenting on that issue because the repro above feels different from the one reported on that issue.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo il report con tmp.py e mypy 0.950 o la versione corrente, concentrandoti su filter con is_not_none e sul TypeGuard TypeVar. Traccia il percorso del controllo dei tipi per l’inferenza della callback di filter e il restringimento di TypeGuard; il lavoro è completato quando l’esempio supera il controllo dei tipi e ints viene accettato come Iterator[int].
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
- Abbastanza chiara
- Idoneità per principianti
- 38/100