我可以从python上下文管理器中检索__exit__的返回值吗?

Len*_*ger 1 python with-statement contextmanager

我在python中使用上下文管理器。想要从我的__exit__方法中获取一些日志。所以我的代码记录如下:

class MyContextManager:
    def __init__(self, value1, value2)
        self.value1 = value1
        self.value2 = value2

    def __enter__(self)
        # Do some other stuff
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Do some tear down action, process some data that is 
        # created in __enter__ and log those results
        return my_results

with MyContextManager(value1=my_value1, value2=my_value2) as manager:
     # Do some stuff
Run Code Online (Sandbox Code Playgroud)

因此,如何访问__exit__with块之后(或末尾)返回的my_results 。在该__exit__方法中返回其他True甚至合法吗?

Mar*_*ers 5

在该__exit__方法中返回其他True甚至合法吗?

不,不是真的,但是Python只会测试true值,因此您可以摆脱它。换句话说,如果您在此处返回真实对象,则所有异常都将被抑制。如果没有例外,则返回真实值只是一个禁忌。

我如何访问__exit__my块之后(或末尾)返回的my_results 。

你不能 的with表达机械消耗它。

您应该以其他方式使它可用。将其设置为上下文管理器对象本身的属性:

class MyContextManager:
    def __init__(self, value1, value2)
        self.value1 = value1
        self.value2 = value2

    def __enter__(self)
        # Do some other stuff
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Do some tear down action, process some data that is 
        # created in __enter__ and log those results
        self.my_results = my_results
        # returning None, we don't want to suppress exceptions
        return None

with MyContextManager(value1=my_value1, value2=my_value2) as manager:
     # Do some stuff

results = manager.my_results
Run Code Online (Sandbox Code Playgroud)

manager名称在with块完成后可用。

例如,unittest.TestCase.assertRaises()上下文管理器就是这样共享捕获的异常的。