为什么 Python 不抛出带有“-> 类型”函数定义的类型异常?

Why Python doesn't throws type exceptions with '-> type' functions definitions?

在其他语言中,与示例类似的任何内容都会引发类型错误。为什么不在 Python 中?

>>> def foo(a:int) -> str:
    return a+1

>>> foo(5)
6

Python 中的类型提示是一个可选添加项,用于帮助静态代码分析和编辑。

来自PEP 484 -- Type Hints specification

Note that this PEP still explicitly does NOT prevent other uses of annotations, nor does it require (or forbid) any particular processing of annotations, even when they conform to this specification. It simply enables better coordination, as PEP 333 did for web frameworks.

While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter. (While it would of course be possible for individual users to employ a similar checker at run time for Design By Contract enforcement or JIT optimization, those tools are not yet as mature.)

请注意,类型提示是 Python 的一个非常新的补充,PEP 旨在 帮助协调 ,而不是强制对语言进行运行时类型检查.

Python 不是 静态类型语言,它仍然是非常动态类型的。您可能会将此功能与静态类型语言中的类型声明混淆。

将来,可能 Python 添加对严格模式的支持(类似于 Hack does this),但这不在table现在。