[Python-ideas] Control Flow - Never Executed Loop Body
Vito De Tullio
vito.detullio at gmail.com
Mon Mar 21 16:57:03 EDT 2016
Chris Angelico 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.
so, the "correct" way to handle this is something like
try:
e = next(iterable)
except StopIteration:
empty_suite() # there is no element
else:
main_suite(e) # handle the first element
for e in iterable:
main_suite(e) # handle the rest of the elements
?
apart for the readability you need to "copy" the same code two times (or
refactor in a function)
--
By ZeD
More information about the Python-ideas
mailing list