我只想退出with
特定条件下的声明:
with open(path) as f:
print 'before condition'
if <condition>: break #syntax error!
print 'after condition'
当然,上面的方法是行不通的。有没有办法做到这一点? (我知道我可以反转条件:if not <condition>: print 'after condition'
——有什么办法像上面那样吗?)
with
给你添麻烦了?扔更多with
- 能够解决问题的对象!
class fragile(object):
class Break(Exception):
"""Break out of the with statement"""
def __init__(self, value):
self.value = value
def __enter__(self):
return self.value.__enter__()
def __exit__(self, etype, value, traceback):
error = self.value.__exit__(etype, value, traceback)
if etype == self.Break:
return True
return error
只需将您要表达的表达式括起来即可with
with fragile
, and raise fragile.Break
随时爆发!
with fragile(open(path)) as f:
print 'before condition'
if condition:
raise fragile.Break
print 'after condition'
此设置的好处
此设置的缺点
- 实际上并没有使用“break”语句。无法赢得所有人;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)