Python 3.6 支持类型注释,例如:
def foo() -> int:
return 42
但是当一个函数没有返回任何东西时,期望使用什么? PEP484示例主要使用 None
作为返回类型,但也有来自 typing
包的 NoReturn
类型。
因此,问题是什么更适合使用以及什么被认为是最佳实践:
def foo() -> None:
#do smth
或
from typing import NoReturn
def foo() -> NoReturn:
#do smth
最佳答案
NoReturn
表示函数从不返回值。
from typing import NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')
也就是说,x = foo_None()
是类型有效的,但值得怀疑,而 x = foo_NoReturn()
是无效的。
除了从来没有可分配的结果,NoReturn
在分支分析中还有其他含义:foo_NoReturn();无法访问..
。 'A NoReturn
type is needed #165' 中有进一步的讨论门票。
In order to perform branch analysis, it is necessary to know which calls will never return normally. Examples are
sys.exit
(which always returns via exception) andos.exit
(which never returns)..
关于python - "void"函数中的 NoReturn 与 None - Python 3.6 中的类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48038149/