python finally可以return吗_python上下文管理中finally块中的Return

我最近在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。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值