[Python-ideas] Control Flow - Never Executed Loop Body
Sven R. Kunze
srkunze at mail.de
Tue Mar 22 08:07:25 EDT 2016
On 21.03.2016 21:57, Vito De Tullio wrote:
> Chris Angelico wrote:
>>
>> 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)
Interesting. I didn't think of this solution.
However, I assume that when I do "object()" I got something unique among
all other objects. So,
item = sentinel = object()
for item in collection:
main_suite(item)
if item is sentinel:
empty_suite()
Is still quite correct, right?
Best,
Sven
More information about the Python-ideas
mailing list