Raf*_*Raf 7 python type-hinting python-typing
这三个函数的返回类型提示有什么区别吗?
def my_func1():
print("Hello World")
return None
def my_func2():
print("Hello World")
return
def my_func3():
print("Hello World")
Run Code Online (Sandbox Code Playgroud)
它们是否都应该有-> None返回类型提示,因为这就是它们实际上显式或隐式返回的内容?或者应该my_func2或my_func3实际上没有返回类型提示?
问这个问题的动机是这个问题,这个很好的答案,以及我正在学习Type Hints的事实。
他们都应该有-> None返回类型,因为他们都清楚地 return None。
请注意,还存在typing.NoReturn实际上从不返回任何内容的函数的类型,例如
from typing import NoReturn
def raise_err() -> NoReturn:
raise AssertionError("oops an error")
Run Code Online (Sandbox Code Playgroud)
其他类型的函数(由@chepner指出)实际上永远不会返回,因此应该进行类型提示,-> NoReturn例如仅结束使用的事件循环sys.exit或任何os.exec*函数
或者应该
my_func2或my_func3实际上没有返回类型提示?
在我看来,他们应该总是有一个类型提示,因为@yedpodtrzitko在他们的回答中所说的那样,没有类型提示的函数默认情况下根本不会被 mypy 进行类型检查,并且它们的返回值基本上被视为他们会被输入为Any. 这大大减少了类型检查的好处,这也是我总是在disallow_untyped_defs = True新项目中使用 mypy 设置的原因之一。
如果你的函数的签名中没有任何类型提示,默认情况下 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
Run Code Online (Sandbox Code Playgroud)
$ mypy ./foo.py
foo.py:6: error: Unsupported operand types for + ("str" and "int")
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)