使用类型库 类 与 Python 类型提示中的类型相比有什么好处?

What is the benefit to using typing library classes vs. types in Python type hints?

我开始学习 Python 中的类型提示,以便将来将代码从 Python 移植到 C。我想知道直接使用类型之间的区别是什么(如果有的话)在类型提示中与使用 typing 模块中定义的 类。

例如

之间的区别
def somefn(a: list[int]) -> tuple[str, int]:
    ...

from typing import List, Tuple

def somefn(a: List[int]) -> Tuple[str, int]:
    ...

似乎 类 像 UnionAnyCallableIterable 会很有用,但 [=30] 的实用性=] 我不清楚 python 中已经作为关键字存在的数据类型。

对于编写可以合法求值的注解很有用;如果您尝试 运行 它 list[int] 将会爆炸,而 typing.List[int] returns 一个新的通用类型,它知道容器和内容的类型。这在 type aliases 的情况下尤为重要,其中泛型的专用版本在顶层定义,然后作为注释进一步重用:

Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
     ...

是合法的,而:

Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
     ...

当着你的面发火。你会注意到 non-container/generic 类型通常没有 typing 类型(像 Text 这样的例外是为了移植问题),因为类型别名只会将它们用作“叶”类型,不是根或分支类型。

更新: 从 3.9 开始,the standard collections can serve as type hints,所以 typing 类型不是绝对必要的;如果你愿意,你可以继续使用它们(对于必须 运行 pre-3.9 Python 的代码是必需的),但如果你可以依赖 3.9+.

则没有必要