[Python-ideas] Control Flow - Never Executed Loop Body
Steven D'Aprano
steve at pearwood.info
Tue Mar 22 19:21:37 EDT 2016
On Tue, Mar 22, 2016 at 06:21:24PM +0100, Sven R. Kunze wrote:
> 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.
Possibly with the exception of the three or four previously existing
easy solutions :-)
> 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.
Does this mean that every single for-loop that doesn't catch
NeverExecuted (or EmptyCollection) will raise an exception?
If not, then how will this work? Is this a special kind of
exception-like process that *only* operates inside for loops?
What will an explicit "raise NeverExecuted" do?
> 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
That doesn't work, for two reasons:
(1) Not all for-loops use iterators. The venerable old "sequence
protocol" is still supported for sequences that don't support __iter__.
So there may not be any StopIteration raised at all.
(2) Even if StopIteration is raised, the for-loop catches it (in a
manner of speaking) and consumes it.
So to have this work, we would need to have the for-loop re-raise
StopIteration... but what happens if you don't include an except
StopIteration clause? Does every bare for-loop with no "except" now
print a traceback and halt processing? If not, why not?
--
Steve
More information about the Python-ideas
mailing list