如何注释可变长度的Python列表

问题描述 投票:0回答:1

如何为可变长度或 None 的 Python 列表编写注释?

当我这样写时,它返回一个错误。

def some_function(params: list[str, ...])  # this gives error: `TypeError: 'type' object is not subscriptable`


def some_function(params: List[str, ...])  # this also gives error: TypeError: Parameters to generic types must be types. Got Ellipsis.

python annotations
1个回答
0
投票

List[str]
list[str]
可以互换使用。列表来自打字模块,因此
List[str]
可能更适合注释。

这意味着,可变长度列表包括一个空列表。

List[Union[str, None]] 不同。这意味着,列表可以包含 None,所以像这样;列表[无,'你好']。

© www.soinside.com 2019 - 2024. All rights reserved.