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

问题描述 投票:6回答:1

Python 3.6支持类型注释,如:

def foo() -> int:
    return 42

但是当函数没有返回任何内容时,预期会使用什么? PEP484的例子大多使用None作为返回类型,但也有来自NoReturn包的typing类型。

所以,问题是什么是更好的使用和什么被认为是最佳实践:

def foo() -> None:
    #do smth

要么

from typing import NoReturn

def foo() -> NoReturn:
    #do smth
python annotations python-3.6 type-hinting typing
1个回答
7
投票

NoReturn表示函数永远不会返回值。

该函数要么不终止,要么总是抛出异常:"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'门票还有进一步的讨论。

为了执行分支分析,有必要知道哪些调用永远不会正常返回。示例是sys.exit(总是通过异常返回)和os.exit(永远不会返回)。

© www.soinside.com 2019 - 2024. All rights reserved.