Top-rated recipes by Andrew Barnert http://code.activestate.com/recipes/users/4184316/top/2015-01-12T22:16:37-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> Equally-spaced numbers (linspace) (Python) 2015-01-12T22:16:37-08:00Andrew Barnerthttp://code.activestate.com/recipes/users/4184316/http://code.activestate.com/recipes/579000-equally-spaced-numbers-linspace/ <p style="color: grey"> Python recipe 579000 by <a href="/recipes/users/4184316/">Andrew Barnert</a> (<a href="/recipes/tags/float/">float</a>, <a href="/recipes/tags/linspace/">linspace</a>, <a href="/recipes/tags/range/">range</a>, <a href="/recipes/tags/spread/">spread</a>). </p> <p>An equivalent of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html"><code>numpy.linspace</code></a>, but as a pure-Python lazy sequence.</p> <p>Like NumPy's <code>linspace</code>, but unlike the <a href="http://code.activestate.com/recipes/577068/"><code>spread</code></a> and <a href="http://code.activestate.com/recipes/577068/"><code>frange</code></a> recipes listed here, the <code>num</code> argument specifies the number of values, not the number of intervals, and the range is closed, not half-open.</p> <p>Although this is primarily designed for floats, it will work for <code>Fraction</code>, <code>Decimal</code>, NumPy arrays (although this would be silly) and even <code>datetime</code> values.</p> <p>This recipe can also serve as an example for creating lazy sequences.</p> <p>See the discussion below for caveats.</p>