Support generic upper bounds
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
Feature
Allow generic upper bounds such as:
class ClassA[T, S: Sequence[T]]: ...
Pitch
PEP 695 has an example that currently doesn't work, and alludes to a future extension to the typesystem that eliminates the limitation:
# The following generates no compiler error, but a type checker
# should generate an error because an upper bound type must be concrete,
# and ``Sequence[S]`` is generic. Future extensions to the type system may
# eliminate this limitation.
class ClassA[S, T: Sequence[S]]: ...
I ran into a usecase for this that I have no way of expressing with the current generics limitations, and generic upper bounds would solve it. I will provide a simpler version of it here so it's easier to discuss.
from typing import Callable, Iterable, Sequence
type CostFunction[T] = Callable[[T], float]
# Sequence[T] gives an error, because T is not concrete
def get_lowest_cost_sequence[T, S: Sequence[T]](
seqs: Iterable[S], item_cost: CostFunction[T]
) -> S:
def seq_cost(seq: S) -> float:
return sum(item_cost(t) for t in seq)
return sorted(seqs, key=seq_cost)[0]
In the example, we are working with sequences, and a cost function for each item in the sequences. The crux is that the function must return the same type as the original sequences. In other words this is an incorrect type signature:
# Return type Sequence[T] is looser, because it does not mean whatever is
# returned will be _the same type_ as what is passed in. Any users of this
# function would have to cast the result for it to expose the same functionality
# as what was in `seqs`.
def get_lowest_cost_sequence[T](
seqs: Iterable[Sequence[T]], item_cost: CostFunction[T]
) -> Sequence[T]:
...
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
No se mencionan archivos de implementación, pruebas ni puntos de entrada. Empieza por la sección «type-parameter-scopes» de PEP 695 y los ejemplos de este Issue, y luego sigue el tratamiento que hace mypy de los límites superiores genéricos; se considera terminado cuando se aceptan los límites genéricos válidos, mientras que los límites no concretos inválidos siguen siendo rechazados, con cobertura de regresión.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- devtools
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100