python / python/typing

Feature Request: Type hint for Fixed Length Homogeneous Sequences

Abierto
#786 7 comentarios 47 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

topic: feature
Lenguaje dominante
Python
Estrellas
1.8k
Forks
302
Merge medio
23 h
PR fusionados (30 d)
8

Descripción

Feature

A concise way to hint that a sequence of homogenous types is a set length. i.e The items in the sequence are all of the same type, the sequence is iterable, and cannot grow larger or smaller.

Pitch

Currently, the recommended way to add type hints to fixed-length sequences is to use Tuples 1. i.e

def foo(ten_floats: Tuple[float,float,float,float,float,float,float,float,float,float]):
    ...

For longer lists, this repetition is tedious and prone to error.
It would be nice to have a shorthand for defining homogeneous tuples. e.g

def foo(ten_floats: HomogeneousTuple[float, 10]):
    ...

Although the name Tuple does not signal intent very well. The real thing that we are trying to signal is that this is a sequence of floats of length 10. It does not necessarily have to be a Tuple, it just has to be iterable, and have 10 items, that cannot grow larger or smaller. If I wanted to pass the function a List, this should also pass static type checkers, as long as it has 10 floats.

Possible Implementation

I am not a core python developer, I have never even looked at the implementation of the typing module, and I'm not even that good of a python developer, so please forgive me if this is nonsense.

In Python 3.10 or newer [2] we will be able to use the unpack operator in subscript. So we might be able to do something like:

_t=[float]*10
def foo(ten_floats: Tuple[*_t]):
    ...

Using TypeVars, we could generalize this function to accept 10 of any type (as long as they are all the same type)

T=TypeVar('T')
TenTypeVars=[T]*10
def foo(ten_homogeneous_items: Tuple[*TenTypeVars]):
    ...

Following this logic, perhaps a generic type hint for Fixed Length Homogeneous Sequences could be implemented with

class FixedLengthHomogeneousSequence(Generic[T, N], Tuple[*[T]*N]):
    ...

FixedLengthHomogeneousSequence is a bit wordy. So perhaps FixedList would be a better name.

[2] (I think this is true). Pylance gave me an error saying this was the case. I think it's related to https://www.python.org/dev/peps/pep-0622/

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

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

El issue no identifica ningún archivo de implementación, prueba ni punto de entrada. Empieza revisando el comportamiento existente del módulo typing para Tuple, TypeVar y las secuencias genéricas, y después compara la sintaxis propuesta con el PEP referenciado; el trabajo estaría terminado cuando haya un diseño acordado para la comprobación de tipos, una ubicación de implementación y pruebas que cubran secuencias homogéneas de longitud fija.

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

Evaluación

Stack tecnológico
python
Área
tooling
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
20/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.