python - 为什么要在 python 3.5 + 中使用类型

标签 python types python-3.5 python-3.6

我试图理解为什么我应该在 python 中使用类型注释。例如,我可以编写如下函数:

def some_function(a: int, b: int) -> int:
    return a + b

当我将它与 int 一起使用时一切都很好:

some_function(1, 2)  # return 3, type int

但是当我运行的时候

some_function(1, 2.0) # return 3.0, type float

我的结果没有任何类型错误的注释。那么使用类型注释的原因是什么?

最佳答案

其他工具 可以使用类型提示来检查您的代码,它们不会在运行时强制执行。目标是使静态分析工具能够检测无效参数的使用。

使用像 PyCharm 这样的 IDE,或者 commandline code checker mypy被告知 2.0 不是有效的参数类型。

来自Type Hinting PEP (484) :

This PEP aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and (perhaps, in some contexts) code generation utilizing type information.

强调我的。运行时类型检查留给第三方工具。请注意,此类运行时检查会带来性能下降,如果您在每次调用时都检查类型,您的代码可能会运行得更慢。

关于python - 为什么要在 python 3.5 + 中使用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460289/

相关文章:

python - 基于循环索引在 Python 中对列表求和

switch 语句中的 Typescript 类型生成问题

xpath - 如何在Python中使用XPath限制特定xml元素的开始和结束标记之间的元素提取范围?

python - 为什么 find_packages 行为取决于 pip 包的导入?

python - python 为什么以及如何截断数值数据?

python - Python中的正斜杠replace()

python - 二维数组的 Numpy Delete

Python:使用 np.savetxt 使用 float 和字符串保存数据

c++ - 检查对象类型真的总是糟糕设计的标志吗?

python - 通过解包计算从 python 字典中读取的内容