pythonpython-3.xtype-hinting

Why can't List contain multiple types?


You can mix types inside tuples or lists. Why can't you specify that in typing hints?

>>> from typing import Tuple, List
>>> t = ('a', 1)
>>> l = ['a', 1]

>>> t2: Tuple[str, int] = ('a', 1)
>>> l2: List[str, int] = ['a', 1]

TypeError: Too many parameters for typing.List; actual 2, expected 1

Solution

  • In type theory, a list is a homogenous structure containing values of one type. As such, List only takes a single type, and every element of that list has to have that type.

    However, type theory also provides sum types, which you can think of as a wrapper around exactly one value selected from some fixed set of types. A sum type is supported by typing.Union. To specify that a list is a mix of int and str values, use

    List[Union[str, int]]
    

    as the type hint.

    By contrast, a tuple is an example of a product type, a type consisting of a fixed set of types, and whose values are a collection of values, one from each type in the product type. Tuple[int,int,int], Tuple[str,int] and Tuple[int,str] are all distinct types, distinguished both by the number of types in the product and the order in which they appear.