python中错误与成功返回值的最佳实践 [英] Best practice in python for return value on error vs. success

查看:76
本文介绍了python中错误与成功返回值的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般中,假设您有一个如下所示的方法.

def intersect_two_lists(self, list1, list2):如果不是list1:self.trap_error("union_two_lists: list1 不能为空.")返回错误如果不是list2:self.trap_error("union_two_lists: list2 不能为空.")返回错误#http://bytes.com/topic/python/answers/19083-standard返回过滤器(列表 1、列表 2 中的 lambda x:x)

在此特定方法中,当发现错误时,我不想在这种情况下返回空列表,因为这可能是此特定方法调用的真正答案,我想返回一些内容以指示参数不正确.所以在这种情况下,我在错误时返回 False,否则返回一个列表(是否为空).

我的问题是,在此类领域的最佳实践是什么,而不仅仅是列表?返回我想要的任何内容并确保我将其记录下来供用户阅读?:-) 你们大多数人做什么:

  1. 如果成功你应该返回 True 或 False 并且你发现一个错误?
  2. 如果成功,您应该返回一个列表,但您发现了错误?
  3. 如果成功您应该返回一个文件句柄并且您发现错误?
  4. 等等

解决方案

首先,无论您做什么,都不会返回结果和错误消息.这是处理错误的一种非常糟糕的方式,会给您带来无尽的头痛.如果您需要指出错误,请始终引发异常.

除非有必要,否则我通常会避免引发错误.在您的示例中,实际上并不需要抛出错误.将空列表与非空列表相交不是错误.结果只是空列表,这是正确的.但是假设您想处理其他情况.例如,如果该方法有一个非列表类型.在这种情况下,最好引发异常.例外没什么好怕的.

我的建议是查看 Python 库中的类似函数,看看 Python 如何处理这些特殊情况.例如看看集合中的交集方法,它往往是宽容的.在这里,我试图将一个空集与一个空列表相交:

<预><代码>>>>b = []>>>一个 = 集()>>>a. 交叉点(b)放([])>>>b = [1, 2]>>>a = set([1, 3])>>>a. 交叉点(b)设置([1])

错误仅在需要时抛出:

<预><代码>>>>乙 = 1>>>a. 交叉点(b)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:int"对象不可迭代

当然,有些情况下成功或失败返回 True 或 False 可能是好的.但保持一致非常重要.该函数应始终返回相同的类型或结构.有一个可以返回列表或布尔值的函数是非常令人困惑的.或者返回相同的类型但是这个值的含义在出错的情况下可以不同.

OP 说:

<块引用>

我想返回一些东西来表明参数不正确.

没有什么比异常更能说明错误的了.如果您想指出参数不正确,请使用异常并提供有用的错误消息.在这种情况下返回结果只是令人困惑.可能还有其他情况,您想表明什么都没有发生,但这不是错误.例如,如果您有一个从表中删除条目的方法,但请求删除的条目不存在.在这种情况下,在成功或失败时只返回 True 或 False 可能没问题.这取决于应用程序和预期行为

In general, let's say you have a method like the below.

def intersect_two_lists(self, list1, list2):
    if not list1:
        self.trap_error("union_two_lists: list1 must not be empty.")
        return False
    if not list2:
        self.trap_error("union_two_lists: list2 must not be empty.")
        return False
    #http://bytes.com/topic/python/answers/19083-standard
    return filter(lambda x:x in list1,list2)

In this particular method when errors are found, I would not want to return the empty list in this case because that could have been the real answer to this specific method call, I want to return something to indicate the parameters were incorrect. So I returned False on error in this case, and a list otherwise (empty or not).

My question is, what is the best practice in areas like this, and not just for lists?Return whatever the heck I want and make sure I document it for a user to read? :-) What do most of you folks do:

  1. If on success you were supposed to return True or False and you catch an error?
  2. If on success you were supposed to return a list and you catch an error?
  3. If on success you were supposed to return a file handle and you catch an error?
  4. et cetera

解决方案

First, whatever you do don't return a result and an error message. That's a really bad way to handle errors and will cause you endless headaches. If you need to indicate an error always raise an exception.

I usually tend to avoid raising errors unless it is necessary. In your example throwing an error is not really needed. Intersecting an empty list with a non empty one is not an error. The result is just empty list and that is correct. But let's say you want to handle other cases. For example if the method got a non-list type. In this case it is better to raise an exception. Exception are nothing to be afraid of.

My advice for you is to look at the Python library for similar functions and see how Python handles those special cases. For example have a look at the intersection method in set, it tends to be forgiving. Here I'm trying to intersect an empty set with an empty list:

>>> b = []
>>> a = set()
>>> a.intersection(b)
set([])

>>> b = [1, 2]
>>> a = set([1, 3])
>>> a.intersection(b)
set([1])

Errors are only thrown when needed:

>>> b = 1
>>> a.intersection(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

Sure, there are cases where returning True or False on success or failure can be good. But it is very important to be consistent. The function should always return the same type or structure. It is very confusing to have a function that could return a list or a boolean. Or return the same type but the meaning of this value can be different in case of an error.

EDIT:

The OP says:

I want to return something to indicate the parameters were incorrect.

Nothing says there is an error better than an exception. If you want to indicate the parameters are incorrect then use exceptions and put a helpful error message. Returning a result in this case is just confusing. There might other cases where you want to indicate that nothing has happened but it is not an error. For example if you have a method that deletes entries from a table and the entry requested for deletion does not exist. In this case it might be fine to just return True or False on success or failure. It depends on the application and the intended behaviour

这篇关于python中错误与成功返回值的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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