带有异常的Python类型提示 [英] Python type hinting with exceptions

查看:116
本文介绍了带有异常的Python类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的函数:

I have a function that looks like this:

def check_for_errors(result):
    if 'success' in result:
        return True

    if 'error' in result:
        raise TypeError

    return False

成功运行此功能,我应该得到一个 bool ,但是如果有一个错误,我应该得到一个 TypeError -这是可以的,因为我在另一个函数中进行了处理。

In successful run of this function, I should get a bool, but if there is an error I should get a TypeError- which is OK because I deal with it in another function.

我的函数为先这行看起来像这样:

My function first line looks like this:

def check_for_errors(result: str) -> bool:

我的问题是:我应该在类型提示中提及错误吗?

My question is: Should I mention the error in my type hinting?

推荐答案

类型提示不能说任何有关异常的内容。它们完全超出了该功能的范围。但是,您仍然可以在文档字符串中记录异常。

Type hinting can't say anything about exceptions. They are entirely out of scope for the feature. You can still document the exception in the docstring however.

来自 PEP 484-提示类型


例外



未提出用于列出显式引发的异常的语法。当前,此功能的唯一已知用例是文档记录,在这种情况下,建议将此信息放入文档字符串中。

Exceptions

No syntax for listing explicitly raised exceptions is proposed. Currently the only known use case for this feature is documentational, in which case the recommendation is to put this information in a docstring.

Guido范·罗瑟姆(van Rossum)强烈反对在类型提示规范中添加异常,因为他不想在需要在每个级别检查(在调用代码中处理)或显式声明异常的情况下结束。

Guido van Rossum has strongly opposed adding exceptions to the type hinting spec, as he doesn't want to end up in a situation where exceptions need to be checked (handled in calling code) or declared explicitly at each level.

这篇关于带有异常的Python类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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