问题描述
受this question和this 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_func2
或my_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_func2
或my_func3
实际上没有返回类型提示吗?
我认为,它们应该总是有类型提示,因为正如@yedpodtrzitko在their 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)