Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify length of Sequence or List with Python typing module

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.

like image 235
John Brodie Avatar asked Jun 29 '17 19:06

John Brodie


People also ask

What is typing module in Python?

Introduced since Python 3.5, Python's typing module attempts to provide a way of hinting types to help static type checkers and linters accurately predict errors.

What is type annotation in Python?

Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.

Should I use type hints Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.

What is type checking in Python?

Python is a dynamically typed language. This means that the Python interpreter does type checking only as code runs, and that the type of a variable is allowed to change over its lifetime.


2 Answers

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.

like image 108
Martijn Pieters Avatar answered Oct 01 '22 19:10

Martijn Pieters


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.

like image 27
Raymond Hettinger Avatar answered Oct 01 '22 20:10

Raymond Hettinger