键入函数永远不会返回的提示 [英] Type hint that a function never returns

查看:36
本文介绍了键入函数永远不会返回的提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 的新类型提示功能允许我们输入提示,函数返回 None...

Python's new type hinting feature allows us to type hint that a function returns None...

def some_func() -> None:
    pass

... 或者不指定返回类型,PEP 规定应该使静态分析器假设任何返回类型都是可能的:

... or to leave the return type unspecified, which the PEP dictates should cause static analysers to assume that any return type is possible:

任何没有注解的函数都应该被视为具有最通用的类​​型

Any function without annotations should be treated as having the most general type possible

但是,我应该如何输入函数永远不会返回的提示?例如,提示这两个函数的返回值的正确方法是什么?

However, how should I type hint that a function will never return? For instance, what is the correct way to type hint the return value of these two functions?

def loop_forever():
    while True:
        print('This function never returns because it loops forever')

def always_explode():
    raise Exception('This function never returns because it always raises')

既不指定 ->在这些情况下,无 或未指定返回类型似乎是正确的.

Neither specifying -> None nor leaving the return type unspecified seems correct in these cases.

推荐答案

即使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.

这篇关于键入函数永远不会返回的提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆