Most viewed recipes tagged "iterable", "with_statement", "iterator" and "context_manager"http://code.activestate.com/recipes/tags/iterable+with_statement+iterator+context_manager/views/2012-11-19T20:10:35-08:00ActiveState Code RecipesWrap any iterable context manager so it closes when consumed (Python)
2012-11-19T20:10:35-08:00Andrew Barnerthttp://code.activestate.com/recipes/users/4184316/http://code.activestate.com/recipes/578342-wrap-any-iterable-context-manager-so-it-closes-whe/
<p style="color: grey">
Python
recipe 578342
by <a href="/recipes/users/4184316/">Andrew Barnert</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/iterable/">iterable</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/with_statement/">with_statement</a>).
</p>
<p>There are a few types in Python—most notably, files—that are both iterators and context managers. For trivial cases, these features are easy to use together, but as soon as you need to use the iterator lazily or asynchronously, a with statement won't help. That's where this recipe comes in handy:</p>
<pre class="prettyprint"><code>send_async(with_iter(open(path, 'r')))
</code></pre>
<p>This also allows you to "forward" closing for a wrapped iterator, so closing the outer iterator also closes the inner one:</p>
<pre class="prettyprint"><code>sync_async(line.upper() for line in with_iter(open(path, 'r')))
</code></pre>