Specify length of Sequence or List with Python typing module Specify length of Sequence or List with Python typing module python python

Specify length of Sequence or List with Python typing module


You can't. A list is a mutable, variable length structure. If you need a fixed-length structure, use a tuple instead:

Tuple[float, float, float, float, float, float, float, float, float, float]

Or better still, use a named tuple, which has both indices and named attributes:

class BunchOfFloats(NamedTuple):    foo: float    bar: float    baz: float    spam: float    ham: float    eggs: float    monty: float    python: float    idle: float    cleese: float

A list is simply the wrong data type for a fixed-length data structure.


So far, only tuples support specifying a fixed number of fields and it has no short-cut for a fixed number of repetitions.

Here's the definition and docstring from the typing module:

class Tuple(tuple, extra=tuple, metaclass=TupleMeta):    """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.    Example: Tuple[T1, T2] is a tuple of two elements corresponding    to type variables T1 and T2.  Tuple[int, float, str] is a tuple    of an int, a float and a string.    To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].    """    __slots__ = ()    def __new__(cls, *args, **kwds):        if _geqv(cls, Tuple):            raise TypeError("Type Tuple cannot be instantiated; "                            "use tuple() instead")        return _generic_new(tuple, cls, *args, **kwds)

Since lists are a mutable, variable-length type, it doesn't make any sense to use a type declaration to specify a fixed size.


Annotated can be handy here. It allows you to specify arbitrary metadata to type hints:

Annotated[List[float], 3]