简体   繁体   English

带有异常的 Python 类型提示

[英]Python type hinting with exceptions

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

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.在这个函数的成功运行中,我应该得到一个bool ,但如果有错误我应该得到一个TypeError - 这没关系,因为我在另一个函数中处理它。

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.但是,您仍然可以在文档字符串中记录异常。

From PEP 484 -- Type Hints :来自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 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. Guido van Rossum 强烈反对在类型提示规范中添加异常,因为他不希望最终陷入需要检查异常(在调用代码中处理)或在每个级别显式声明的情况。

It is usually a good idea to document the error.记录错误通常是个好主意。 This means that another developer using your function will be able to handle your errors without having to read through your code.这意味着使用您的函数的其他开发人员将能够处理您的错误,而无需通读您的代码。

我通常使用:

 def check_for_errors(result: str) -> bool | YourException:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM