python3中的静态类型:列表与列表

Jus*_*tin 11 python static-typing list python-3.x

例如在python3中定义函数的参数时,使用list和List有什么区别?例如,有什么区别

def do_something(vars: list):
Run Code Online (Sandbox Code Playgroud)

def do_something(vars: List):
Run Code Online (Sandbox Code Playgroud)

文件说:

类打字。列表(列表,MutableSequence[T])

列表的通用版本。用于注释返回类型。

但我不完全确定以上是什么意思。

我有类似的问题:dict vs dict、set vs set等。

Pat*_*ugh 10

从打字的角度来看,并非所有列表都相同。该程序

def f(some_list: list):
    return [i+2 for i in some_list]

f(['a', 'b', 'c'])
Run Code Online (Sandbox Code Playgroud)

不会使静态类型检查器失败,即使它不会运行。相比之下,您可以使用以下抽象类型指定列表的内容typing

def f(some_list: List[int]) -> List[int]:
    return [i+2 for i in some_list]

f(['a', 'b', 'c'])
Run Code Online (Sandbox Code Playgroud)

会失败,因为它应该。

  • @ScottJ @SearchSpace 只需阅读文档即可。https://docs.python.org/3/library/typing.html#special-forms 自 Python 3.9 起,所有类型如 `List`、`Dict` 等(大写字母)均已弃用,例如 `自版本以来已弃用3.9:builtins.tuple 现在支持 []。请参阅 PEP 585 和通用别名类型。您可以仅使用“list”。如果您需要使用旧类型,则保留它们是为了向后兼容。 (9认同)
  • 注意:PEP 585 在 Python 3.9 中更改了这一点。小写的“list[int]”现在可以使用。 (5认同)
  • @ScottJ 那么 list 和 List 现在完全一样了吗? (3认同)