Description
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/