[Python-ideas] Control Flow - Never Executed Loop Body

Michael Selik mike at selik.org
Thu Mar 24 18:21:45 EDT 2016


On Thu, Mar 24, 2016 at 6:14 PM Michael Selik <mike at selik.org> wrote:

> On Thu, Mar 24, 2016 at 5:34 PM Chris Barker <chris.barker at noaa.gov>
> wrote:
>
>> From the perspective of many, many (most?) people.  I use for loops and
>>> while loops *alot*, and I can count the times I have wanted to use the
>>> `else` clause in the meaning of "all my tests failed, so do this block" on
>>> the fingers of one hand.
>>
>>
>> I"ve only used for .. else a handful of times, and honestly, probably
>> forgot to use it when it would have been the right way to do something far
>> more times :-)
>>
>> but I can't think of a SINGLE time when I wanted to know that the loop
>> didn't run because it's iterable was empty.
>>
>
> More specifically, a time when the loop didn't run because the iterable
> was empty AND the iterable didn't have a len to make that a simple check.
>
> Which suddenly gives me an idea...
>
>     class Peeking:
>
>         def __init__(self, iterator):
>             self.it = iter(iterator)
>             self.sentinel = object()
>             self.buf = next(self.it, self.sentinel)
>
>         def __iter__(self):
>             return self
>
>         def __next__(self):
>             if self.buf is self.sentinel:
>                 raise StopIteration
>             value = self.buf
>             self.buf = next(self.it, self.sentinel)
>             return value
>
>         def __bool__(self):
>             return self.buf is not self.sentinel
>
>
> If you find yourself in a situation where you want to check empty as if
> your iterator was a sequence (ie. len(seq) == 0 means False), give this
> wrapper a shot just before you do the loop.
>
>     >>> bool(Peeking(range(0)))
>     False
>     >>> bool(Peeking(range(1)))
>     True
>
> We could even make it a context manager to monkey-patch a buffering inside
> the context for the bool check, then undo the patch on leaving the context
> to stop buffering.
>

Whoops, got the True/False accidentally flipped. Still, I think the example
gets the point across.

Aside: the PSF should probably buy the "self.it" domain name to take
advantage of Gmail's auto-linking.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160324/6d609133/attachment-0001.html>


More information about the Python-ideas mailing list