python 中包含 0 个或多个项目的字符串列表的类型提示

Type hint for a list of string with 0 or more items in python

我有一个列表,可以是这样的:

a_list = ["apple"]

a_list = []

在这种情况下,类型提示可以是 List[str]List[Optional[str]]。哪个是该变量的适当类型提示,为什么?

谢谢!

List[str] 包括所有字符串列表,包括空列表。 (从类型的角度来看,List[str] 类型的空列表不同于 List[int] 类型的空列表)。

Optional[str] 是 shorthand for Union[None, str],所以 List[Optional[str]] 是可以包含 str 值和 Nones 的列表类型,而不是可能有也可能没有 str 值的列表类型。