为什么 return 类型没有在 python3 中检查?

Why return type is not checked in python3?

示例来自 PEP 484 -- Type Hints

def greeting(name: str) -> str:
    return 'Hello ' + name

用str调用函数的正确方法

>>> greeting("John")
'Hello John'

如果我用 int 调用它:

>>> greeting(2)
TypeError: must be str, not int

用列表调用

>>> greeting(["John"])
TypeError: must be str, not list

一切正常吧? greeting 函数始终接受 str 作为参数。

但是如果我尝试测试函数 return 类型,例如,使用相同的函数但将 return 类型更改为 int。

def greeting(name: str) -> int:
    return 'Hello ' + name

函数 returns str 但类型定义为 int,并且没有引发异常:

>>> greeting("John")
'Hello John'

另一个例子:

def greeting(name: str) -> str:
    return len(name)

>>> greeting("John")
4

虽然 PEP 484 说 return 类型应该是 str,但它实际上并不类似于上面示例中的参数类型检查。

This states that the expected type of the name argument is str. Analogically, the expected return type is str.

我是不是遗漏了什么,或者没有 return 类型的类型检查?

PEP 的 abstract 指出:

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.)

这个问题可能会让新手对 python3 输入提示有点困惑。 python3 中没有类型检查支持。这意味着如果您在参数中传递了不正确的类型,python 解释器将不会引发异常。

如果您需要此功能,可以使用

mypy

在上面的示例中引发 TypeError 的实际原因是 (+) 运算符的不安全使用。 如果您使用字符串格式

更改示例中提供的函数
def greeting(name: str) -> str:
    return 'Hello {}'.format(name)

以上所有情况都可以在不引发 TypeError 的情况下运行,并且在运行时不会进行类型检查。

类型提示被 IDE 像 PyCharm、PyCharm Type Hinting 使用,但它只是 IDE 显示的警告,而不是由 python 解释器显示.