Popular recipes tagged "truth"http://code.activestate.com/recipes/tags/truth/2013-06-11T08:00:25-07:00ActiveState Code RecipesTruth Value Aware Iterable (Python)
2013-06-11T08:00:25-07:00Alan Franzonihttp://code.activestate.com/recipes/users/4169882/http://code.activestate.com/recipes/578549-truth-value-aware-iterable/
<p style="color: grey">
Python
recipe 578549
by <a href="/recipes/users/4169882/">Alan Franzoni</a>
(<a href="/recipes/tags/boolean/">boolean</a>, <a href="/recipes/tags/iterable/">iterable</a>, <a href="/recipes/tags/truth/">truth</a>).
</p>
<p>This small recipe enables truth value testing on iterables.</p>
<p>It is quite common to do things like:</p>
<pre class="prettyprint"><code>if somesequence:
...
else:
...
</code></pre>
<p>Such constructs, that enter the if block if the sequence's got one or more elements and the else block if it's empty, work fine on non-lazy builtin sequences (lists, strings, tuples) and dictionaries as well, but doesn't necessarily work on generic iterables - most of them are always true regardless of their contents, since they're some kind of object. A classical example is generators, but such behaviour can be extended to any object implementing the Iterable interface.</p>
<p>Just wrap your iterable with this decorator and you'll get a truth-aware iterable which supports proper truth testing by doing a small first element prefetching and can then be used just like the original iterable.</p>