Is there a meaningful way to use context managers inside generators?
<pre><code>from contextlib import contextmanager

@contextmanager
def context():
    print "entering"
    yield
    print "exiting"

def test():
    with context():
        for x in range(10):
            yield x

for x in test():
    if x == 5:
        break  # or raise
</code></pre>

<p>The output of this program is simply "entering".</p>

<p>Is there a way to make python automatically invoke the <code>__exit__</code> method of context() when the <code>for</code>-loop is interrupted? Or some other way of achieving the same aim? What I know about generators and context managers makes me suspect it's not possible, but this makes context managers rather useless inside generators, doesn't it? It seems to me, a <code>yield</code> statement inside a <code>with</code> block should raise a red flag, <strong>context manager <code>__exit__</code> may not run</strong>.</p>
