Skip to main content
 首页 » 编程设计

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

2025年05月04日22emanlee

我在 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 

那么我如何访问在我的 with block 之后(或末尾)从 __exit__ 返回的 my_results。在 __exit__ 方法中返回 True 以外的东西是否合法?

请您参考如下方法:

Is this even legit to return something other the True in the __exit__ method?

不,不是真的,但是 Python 只会测试 truth value ,所以你可以摆脱它。换句话说,如果你在这里返回一个 truthy 对象,任何异常都会被抑制。如果没有异常,返回真值只是一个空操作。

how could I access my_results which is returned from __exit__ after (or at the end) of my with block.

你不能。 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 

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

这就是 unittest.TestCase.assertRaises() context manager 的方式例如,共享捕获的异常。