且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

键入函数永远不会返回的提示

更新时间:2023-12-04 23:25:16

即使PEP 484 — 类型提示"标准在问题和答案中都提到,但没有人引用它的部分:涵盖您的问题的 NoReturn 类型.

Even though "PEP 484 — Type Hints" standard mentioned both in question and in the answer yet nobody quotes its section: The NoReturn type that covers your question.

引用:

typing 模块提供了一个特殊类型 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')

该部分还提供了错误用法的示例.虽然它没有涵盖具有无限循环的函数,但在类型理论中,它们都同样满足 never return 由该特殊类型表达的含义.

The section also provides examples of the wrong usages. Though it doesn’t cover functions with an endless loop, in type theory they both equally satisfy never returns meaning expressed by that special type.