如何为可变长度或 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.
List[str]
和 list[str]
可以互换使用。列表来自打字模块,因此 List[str]
可能更适合注释。
这意味着,可变长度列表包括一个空列表。
List[Union[str, None]] 不同。这意味着,列表可以包含 None,所以像这样;列表[无,'你好']。