问题
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
回答1:
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.
回答2:
You could use a Union
, but generally, if you can avoid it, lists should be homogenous instead of heterogeneous:
from typing import List, Union
lst: List[Union[str, int]] = [1, 'a']
myp
, at least, will accept this just fine.
This means though that your list accessors will return a Union type, often necessitating handling different possible types in any downstream functions. Accepting unions is generally less problematic.
来源:https://stackoverflow.com/questions/53526516/why-cant-list-contain-multiple-types