Empty Collection Handling with `next`
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 5.1k
- Fork
- 2.1k
- Merge medio
- 1g 19h
- PR unite (30g)
- 82
Descrizione
There are some issues when using next when providing an empty collection as a default, let's take this example:
from collections.abc import Iterable
def foo(iter: Iterable[list[int]]) -> None:
next((item for item in iter if len(item) > 5), [])
This leads to errors in Pyright, as [] is treated as list[unknown]. Pyright Playground.
Here are the current next overloads:
@overload
def next(i: SupportsNext[_T], /) -> _T: ...
@overload
def next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ...
I would propose changing the second one to:
def next(i: SupportsNext[_T], default: _VT | _T, /) -> _T | _VT: ...
This would fix the above issue, as in the case an empty list or othe rcollection Pyright could just infer the type as _T, while not disrupting other cases in which the types differ.
With this change in Pyright:
from typing import reveal_type
def foo(iter: Iterable[list[int]]) -> None:
result = next((item for item in iter if len(item) > 5), [])
reveal_type(result) # Revealed type is `list[int]`.
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 con i due overload attuali di next mostrati nell’issue e riproduci l’esempio nel Pyright Playground collegato. Confronta il tipo inferito con l’aspettativa di reveal_type; il lavoro è completato quando il valore predefinito vuoto viene accettato e il risultato viene inferito come list[int], senza alterare i casi con tipi di valore predefinito differenti.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- tooling
- Tipo di issue
- Bug
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Stato di attività
- Ferma
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 52/100