我最近在Python的with语句中遇到了一个奇怪的行为。我有一段代码,它使用Python的上下文管理器来回滚__exit__方法中的配置更改。管理器在__exit__中的finally块中有一个return False值。我在下面的代码中隔离了这种情况—唯一的区别是return语句的缩进:class Manager1(object):
def release(self):
pass # Implementation not important
def rollback(self):
# Rollback fails throwing an exception:
raise Exception("A failure")
def __enter__(self):
print "ENTER1"
def __exit__(self, exc_type, exc_val, exc_tb):
print "EXIT1"
try:
self.rollback()
finally:
self.release()
return False # The only difference here!
class Manager2(object):
def release(self):
pass # Implementation not important
def rollback(self):
# Rollback fails throwing an exception:
raise Exception("A failure")
def __enter__(self):
print "ENTER2"
def __exit__(self, exc_type, exc_val, exc_tb):
print "EXIT2"
try:
self.rollback()
finally:
self.release()
return False # The only difference here!
在上面的代码中,回滚失败,出现异常。我的问题是,为什么Manager1的行为与Manager2不同。异常不会在Manager1中的with语句之外引发,以及在Manager2中退出时引发异常的原因。在
^{pr2}$
If an exception is supplied, and the method wishes to suppress the
exception (i.e., prevent it from being propagated), it should return a
true value. Otherwise, the exception will be processed normally upon
exit from this method.
在我看来,在这两种情况下,退出都不返回True,因此在这两种情况下都不应取消该异常。但在Manager1中却是如此。有人能解释一下吗?在
我使用python2.7.6。在