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 fragile(open(path1)) as f:
with fragile(open(path2)) as g:
print f.read()
print g.read()
raise fragile.Break
print "This wont happen"
print "This will though!"
最好的方法是将其封装在函数中并使用
return
:给你添麻烦?在这个问题上抛出更多的
with
对象!只要用
fragile
来包装你要with
的表达式,然后raise fragile.Break
就可以在任何时候爆发!此设置的好处
with
,并且仅使用with
;不会将函数包装在语义上具有误导性的一次运行“循环”或狭义专用的函数中,也不会强制您在with
之后执行任何额外的错误处理。舒适!
这样,如果您希望两者都断开,就不必创建新函数来包装外部
with
。fragile
包装好你已经拥有的东西,你就可以走了!这种设置的缺点
我认为你应该调整一下逻辑:
相关问题 更多 >
编程相关推荐