2017-09-06 81 views
1

我在python中使用上下文管理器。在想从我的__exit__方法中获取一些日志。所以,我的代码记录是这样的:我可以从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 

因此,如何我可以访问它从__exit__与块返回后(或结尾)我的my_results。这是否合法返回__exit__方法中的其他值True?

回答

3

这甚至合法的返回其他东西在__exit__方法真?

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

我怎样才能访问my_results,这个my_results从我的block后面(或结束时)返回的__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 
     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块完成后。

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

+0

非常感谢!有用的信息! :)我不知道MyContextManager的实例在with块后仍然存在。 –

+0

很高兴有帮助!如果您觉得它对您有用,请随时[接受我的回答](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 :-) –

相关问题