使用 List/Tuple/etc。从键入 vs 直接引用类型 list/tuple/etc

Using List/Tuple/etc. from typing vs directly referring type as list/tuple/etc

typing模块使用ListTuple等有什么区别:

from typing import Tuple

def f(points: Tuple):
    return map(do_stuff, points)

与直接引用 Python 的类型相反:

def f(points: tuple):
    return map(do_stuff, points)

我什么时候应该用一个代替另一个?

直到 Python 3.9 added support for type hinting using standard collections,你必须使用 typing.Tupletyping.List 如果你想记录什么类型的 contents 个容器需要:

def f(points: Tuple[float, float]):
    return map(do_stuff, points)

直到 Python 3.8,tuplelist 不支持成为 used as generic types。上面的示例记录了函数 f 要求 points 参数是一个具有两个 float 值的元组。

typing.Tuple 在这里很特别,因为它允许您指定特定数量的预期元素和每个位置的类型。如果未设置长度且应重复类型,请使用省略号:Tuple[float, ...] 描述了可变长度 tuplefloats。

对于typing.List and other sequence types you generally only specify the type for all elements; List[str] is a list of strings, of any size. Note that functions should preferentially take typing.Sequence作为参数而typing.List通常只用于return类型;一般来说,大多数函数会采用任何序列并且只会迭代,但是当您 return 一个 list 时,您实际上是在 return 一个特定的可变序列类型。

如果您仍然需要支持 Python 3.8 或更早的代码,您应该始终选择 typing 泛型,即使您当前没有限制内容。稍后使用泛型类型添加该约束会更容易,因为结果更改会更小。

如果您要实现自定义容器类型并希望该类型支持泛型,您可以 implement a __class_getitem__ hook or inherit from typing.Generic(它又实现了 __class_getitem__)。

从 Python 3.9 (PEP 585) 开始 tuplelist 和其他各种 类 现在是通用类型。现在首选使用这些而不是 typing 对应物。从 Python 3.9 开始,您现在可以这样做:

def f(points: tuple[float, float]):
    return map(do_stuff, points)

如果您不需要评估类型提示,那么由于 PEP 563.

,您可以在 Python 3.7+ 中使用此语法
from __future__ import annotations


def f(points: tuple[float, float]):
    return map(do_stuff, points)

您应该尽可能选择非 typing 泛型,因为旧的 typing.Tupletyping.Listother generics 已弃用,将在以后的版本中删除Python.

Importing those from typing is deprecated. Due to PEP 563 and the intention to minimize the runtime impact of typing, this deprecation will not generate DeprecationWarnings. Instead, type checkers may warn about such deprecated usage when the target version of the checked program is signalled to be Python 3.9 or newer. It's recommended to allow for those warnings to be silenced on a project-wide basis.

The deprecated functionality will be removed from the typing module in the first Python version released 5 years after the release of Python 3.9.0.