python / python/typeshed

Empty Collection Handling with `next`

Abierto
#12,064 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Lenguaje dominante
Python
Estrellas
5.1k
Forks
2.1k
Merge medio
1 d 19 h
PR fusionados (30 d)
82

Descripción

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]`.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con las dos sobrecargas actuales de next mostradas en el issue y reproduce el ejemplo en el Pyright Playground enlazado. Compara el tipo inferido con la expectativa de reveal_type; estará listo cuando se acepte el valor predeterminado vacío y el resultado se infiera como list[int] sin afectar a los casos con tipos de valor predeterminado diferentes.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
tooling
Tipo de issue
Error
Dificultad
2/5
Tiempo estimado
1-3 horas
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
52/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.