NoReturn 与 "void" 函数中的 None - 在 Python 3.6 中键入注释

NoReturn vs. None in "void" functions - type annotations in Python 3.6

Python 3.6支持类型注解,如:

def foo() -> int:
    return 42

但是当一个函数没有 return 任何东西时,期望使用什么? PEP484 示例主要使用 None 作为 return 类型,但也有 typing 包中的 NoReturn 类型。

所以,问题是什么更适合使用,什么被认为是最佳实践:

def foo() -> None:
    #do smth

from typing import NoReturn

def foo() -> NoReturn:
    #do smth

NoReturn 表示函数 永远不会 returns 一个值 .

函数不终止或总是抛出异常"The typing module provides a special type NoReturn to annotate functions that never return normally. For example, a function that unconditionally raises an exception.."

from typing import NoReturn

def stop() -> NoReturn:
    raise RuntimeError('no way')

也就是说,x = foo_None() 类型有效但可疑,而 x = foo_NoReturn() 无效。

除了从来没有可分配的结果外,NoReturn 在分支分析中还有其他含义:foo_NoReturn(); unreachable..'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) and os.exit (which never returns)..