NoReturn vs. None in “void"函数 - Python 3.6 中的类型注释 [英] NoReturn vs. None in "void" functions - type annotations in Python 3.6
问题描述
Python 3.6 支持类型注解,比如:
Python 3.6 supports type annotation, like:
def foo() -> int:
return 42
但是当一个函数没有返回任何东西时,应该使用什么?PEP484 示例大多使用 None
作为返回类型,但也有来自 typing
包的 NoReturn
类型.
But what is expected to use when a function hasn't return anything? PEP484 examples mostly use None
as a return type, but there is also NoReturn
type from typing
package.
因此,问题是什么更可取,什么被认为是最佳实践:
So, the question is what is preferable to use and what is considered a best practice:
def foo() -> None:
#do smth
或
from typing import NoReturn
def foo() -> NoReturn:
#do smth
推荐答案
NoReturn
表示函数从不返回值.
函数要么不终止,要么总是抛出异常:"typing 模块提供了一个特殊的类型 NoReturn 来注释永远不会正常返回的函数.例如,一个无条件引发异常的函数.......
from typing import NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')
也就是说,x = foo_None()
是类型有效但可疑的,而 x = foo_NoReturn()
是无效的.
That is, x = foo_None()
is type-valid but suspect while x = foo_NoReturn()
is invalid.
除了从来没有可赋值的结果外,NoReturn
在分支分析中还有其他含义:foo_NoReturn();无法访问..
.在 'A NoReturn
类型是需要的#165'中有进一步的讨论门票.
Besides never having an assignable result, NoReturn
also has other implications in branch analysis: foo_NoReturn(); unreachable..
. There is further discussion in the 'A NoReturn
type is needed #165' ticket.
为了进行分支分析,需要知道哪些调用永远不会正常返回.例如 sys.exit
(总是通过异常返回)和 os.exit
(从不返回).
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)..
这篇关于NoReturn vs. None in “void"函数 - Python 3.6 中的类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!