问题描述
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表示函数从不返回值.
NoReturn means the function never returns a value.
函数不会终止或总是引发异常:"键入模块提供特殊类型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(); unreachable..
. 需要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.
这篇关于NoReturn与"void"中的None函数-Python 3.6中的类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!