Specify length of Sequence or List with Python typing module

John Brodie picture John Brodie · Jun 29, 2017 · Viewed 11.7k times · Source

I'm giving the Python typing module a shot.

I know that it's valid to specify the length of a List like the following*:

List[float, float, float]   # List of 3 floats <-- NOTE: this is not valid Python

Is there any shorthand for longer lists? What if I want to set it to 10 floats?

List[float * 10]   # This doesn't work.

Any idea if this is possible, this would be handy.


*NOTE: It turns out that supplying multiple arguments to Sequence[] (and its subclasses) in this manner is currently NOT valid Python. Furthermore, it is currently not possible to specify a Sequence length using the typing module in this way.

Answer

Martijn Pieters picture Martijn Pieters · Jun 29, 2017

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.