我试图理解为什么我应该在 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
不是有效的参数类型。
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/