[Python-ideas] Control Flow - Never Executed Loop Body
Sven R. Kunze
srkunze at mail.de
Tue Mar 22 13:21:24 EDT 2016
On 22.03.2016 16:09, Stephen J. Turnbull wrote:
> Chris Barker writes:
> > All that being said:
> >
> > how about "elempty"?, to go with elif?
>
> -1 Not to my taste, to say the least.
Hmm, it seems there is no easy solution for this. What do you think
about an alternative that can handle more than empty and else?
for item in collection:
# do for item
except NeverExecuted:
# do if collection is empty
It basically merges "try" and "for" and make "for" emit EmptyCollection.
So, independent of the initial "never executed loop body" use-case, one
could also emulate the "else" clause by:
for item in collection:
# do for item
except StopIteration:
# do after the loop
Thinking this further, it might enable much more use-cases and stays
extensible without the need to invent all kinds of special keywords.
So, this "for" might roughly be equivalent to (using the "old for"):
class NeverExecuted(StopIteration):
pass
i = iter(collection)
try:
e = next(i)
except StopIteration:
if [NeverExecuted/StopIteration is catched]:
raise NeverExecuted
else:
# do for item e
for e in i:
# do for item e
else:
if [StopIteration is catched]:
raise StopIteration
I hope that's not too convoluted.
Best,
Sven
More information about the Python-ideas
mailing list