[Python-ideas] Control Flow - Never Executed Loop Body
Michael Selik
mike at selik.org
Wed Mar 23 14:19:12 EDT 2016
> On Mar 23, 2016, at 1:13 PM, Henshaw, Andy <Andy.Henshaw at gtri.gatech.edu> wrote:
>
>> -----Original Message-----
>>
>> On Mon, Mar 21, 2016 at 7:01 PM, Stephen J. Turnbull
>> <stephen at xemacs.org> wrote:
>>> item = _sentinel = object()
>>> for item in iterable:
>>> # do for each item
>>> if item is _sentinel:
>>> # do exactly when iterable raises StopIteration on the first
>>> pass
>>
>> What if 'iterable' is locals().values()? Can you, with perfect reliability,
>> recognize that case? AIUI this is exactly why next() and
>> __next__() are defined to "return a value or raise", rather than "return a
>> value or return a magic no-more-values value", because there's always the
>> possibility that the no-more-values value is a legitimately-yielded value.
>>
>> Maybe this situation isn't important enough or common enough to justify
>> dedicated syntax, but it's definitely a possibility.
>>
>> ChrisA
>
> is_empty = True
> for item in iterable:
> is_empty = False
> # do for each item
> if is_empty:
> # do exactly when iterable raises StopIteration on the first
>
> Maybe I'm missing something, but this seems to be an unnecessary addition.
It’s comparable in purpose to the ``else`` clause on a ``for`` or ``while``. It eliminates the need for a flag variable, like ``was_completed`` or ``is_empty``. It saves two lines of code, but more importantly avoids the accidental flip of True/False when setting the flag variable. Whether that warrants adding new syntax... I’m not convinced by the current proposals, but I can imagine finding a good keyword for the purpose. A keyword as good as ``else`` at least.
More information about the Python-ideas
mailing list