输入提示返回的提示,返回无,并且根本不返回?

问题描述

this questionthis nice answer的启发,并且由于我正在学习Type Hints,这三个函数之间的返回类型提示是否有所不同?

def my_func1():
    print("Hello World")
    return None

def my_func2():
    print("Hello World")
    return

def my_func3():
    print("Hello World")

它们都应该有-> None返回类型提示,因为这是显式或隐式返回的内容吗?还是my_func2my_func3实际上没有返回类型提示?

解决方法

它们都应该具有-> None返回类型,因为它们都明显返回了None

请注意,对于实际上从不返回任何内容的函数,也存在typing.NoReturn类型,例如

from typing import NoReturn

def raise_err() -> NoReturn:
    raise AssertionError("oops an error")

其他类型的函数(由@chepner指出)实际上永不返回,因此应以-> NoReturn进行类型提示,例如,事件循环仅以sys.exit或任何os.exec*函数

或者my_func2my_func3实际上没有返回类型提示吗?

我认为,它们应该总是有类型提示,因为正如@yedpodtrzitkotheir answer中所说,没有类型提示的函数默认情况下不会由mypy检查类型根本没有考虑它们的返回值,就好像它们将被键入为Any一样。这大大降低了类型检查的好处,这就是我一直在新项目中使用mypy设置disallow_untyped_defs = True的原因之一。

,

如果函数的签名中没有任何类型提示,则mypy默认不会检查它们。考虑以下内容:

$ cat foo.py

def foo():
    """this function has no type hint in its signature 
    it won't be checked and the error will be ignored."""
    "foo" + 1
    return None

def bar() -> None:
    """this has type hint in the signature
    it will be checked and error will be reported"""
    "bar" + 1
    return None
$ mypy ./foo.py
foo.py:6: error: Unsupported operand types for + ("str" and "int")
Found 1 error in 1 file (checked 1 source file)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...