【问题标题】:What is the benefit to using typing library classes vs. types in Python type hints?在 Python 类型提示中使用类型库类与类型相比有什么好处?
【发布时间】:2018-05-20 21:04:18
【问题描述】:

我开始学习 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 之类的类会很有用,但我不清楚对于 Python 中已经作为关键字存在的数据类型的类的实用性。

【问题讨论】:

    标签: python type-hinting static-typing


    【解决方案1】:

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

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

    是合法的,而:

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

    在你的脸上炸开。您会注意到,非容器/泛型类型通常没有 typing 类型(Text 等例外是用于移植问题),因为类型别名只会将它们用作“叶”类型,而不是根或分支类型。

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

    【讨论】:

      猜你喜欢
      • 2017-06-08
      • 2016-11-08
      • 1970-01-01
      • 2018-02-23
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2022-01-23
      相关资源
      最近更新 更多