编程语言
首页 > 编程语言> > 在Python2.7上下文管理器类中处理异常的正确方法

在Python2.7上下文管理器类中处理异常的正确方法

作者:互联网

我正在为一个正在研究的项目提供几个上下文管理器.它即将发货,我遇到了一些我开始恐慌的事情.

我的印象是你不应该再加上作为上下文管理器类的__exit__方法的参数传递的异常.但是,我正在进行一些测试,看起来上下文管理器正在抑制一个被抛入其中的异常.当我将__exit__方法更改为如下所示时:

def __exit__(self, type_, value, trace):
    if trace is not None:
        print('ERROR IN TRACEBACK: ' + str(value))
        # PYTHON 2.7 RAISE SYNTAX:
        raise type_, value, trace

这些错误似乎正确地通过了.

我的问题是:如果type_,value和trace不是None,那么在__exit__方法中处理异常的正确方法是什么?提升(重新加注?)这样的例外是不是很糟糕?
这是我应该怎么做的?

我遇到的错误可能是由其他原因造成的.通常我会仔细检查这一切,但我的时间似乎非常有限.我希望有人可以解释这个功能的正确实现

最后:
我可以在上下文管理器__exit__方法中安全地保留raise type_,value,trace吗?

解决方法:

__exit__方法的返回值应指示是否应该重新引发传递给它的异常(每个the docs):

contextmanager.__exit__(exc_type, exc_val, exc_tb)

Exit the runtime context and return a Boolean flag indicating if any
exception that occurred should be suppressed. If an exception occurred
while executing the body of the with statement, the arguments contain
the exception type, value and traceback information. Otherwise, all
three arguments are None.

因此,只要您的__exit__方法返回False-y,就应该重新引发异常而不显式执行任何操作.

此外,docs explicilty声明不要自己重新提出异常:

The exception passed in should never be reraised explicitly – instead,
this method should return a false value to indicate that the method
completed successfully and does not want to suppress the raised
exception. This allows context management code (such as
contextlib.nested) to easily detect whether or not an __exit__()
method has actually failed.

标签:python,exception-handling,contextmanager
来源: https://codeday.me/bug/20190612/1225060.html