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

标签 python exception-handling contextmanager

我有几个上下文管理器用于我正在处理的项目。它即将发货,我遇到了一些让我开始 panic 的事情。

我的印象是您不应该重新引发作为参数传递给上下文管理器类的 __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__ 方法中处理异常的正确方法是什么?像这样引发(重新引发?)异常不好吗? 这是我应该做的吗?

我遇到的错误可能是由其他原因引起的。通常我会仔细检查并彻底测试这一切,但目前我的时间似乎非常有限。我希望有人可以解释这个函数的正确实现和

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

最佳答案

__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,就应该在您不明确执行任何操作的情况下重新引发异常。

此外,文档明确声明自己重新引发异常:

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 - Python2.7 上下文管理器类中处理异常的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24686329/

相关文章:

python - TensorFlow 中损失函数 (MLP) 的奇怪 NaN 值

python - 将 optparse 输入插入函数调用

python - 如何在 Python 中获取完整的异常堆栈跟踪

python - 为 zipfile 定义的 __enter__ 和 __exit__ 在哪里?

python - 在 contextmanager 中使用 yield 两次

python - 如何找到多个文档中存在的所有最长公共(public)子串?

python - 计算范围 (0,n] 中数字 'x' 的出现次数

json - 在 JSON.parse 期间在 Node 中捕获异常

python - 在 python 2.5 中打印有关异常的信息?

python - 将多个函数包装在同一个 with 语句中的 pythonic 方法是什么