<p>给你添麻烦?在这个问题上抛出更多的<code>with</code>对象!</p>
<pre><code>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
</code></pre>
<p>只要用<code>fragile</code>来包装你要<code>with</code>的表达式,然后<code>raise fragile.Break</code>就可以在任何时候爆发!</p>
<pre><code>with fragile(open(path)) as f:
print 'before condition'
if condition:
raise fragile.Break
print 'after condition'
</code></pre>
<h3>此设置的好处</h3>
<ul>
<li>使用<code>with</code>,并且仅使用<code>with</code>;不会将函数包装在语义上具有误导性的一次运行“循环”或狭义专用的函数中,也不会强制您在<code>with</code>之后执行任何额外的错误处理。</li>
<li>保持局部变量可用,而不必将它们传递给包装函数。</li>
<li><p>舒适!</p>
<pre><code>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!"
</code></pre>
<p>这样,如果您希望两者都断开,就不必创建新函数来包装外部<code>with</code>。</p></li>
<li>完全不需要重组:只要用<code>fragile</code>包装好你已经拥有的东西,你就可以走了!</li>
</ul>
<h3>这种设置的缺点</h3>
<ul>
<li>实际上不使用“break”语句。不可能全部赢;)</li>
</ul>