[Python-ideas] Control Flow - Never Executed Loop Body
Chris Angelico
rosuav at gmail.com
Sun Mar 20 21:52:20 EDT 2016
On Mon, Mar 21, 2016 at 12:32 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> That's one way of thinking about it. But I don't think it is helpful to
> think of it as setting an invisible flag "a break was hit inside the
> loop", and then testing it. I think that a more natural way to think
> about it is that "break" jumps out of the entire for...else compound
> statement. This has the big advantage that it actually matches what the
> byte code does in all the versions I've looked at.
Exactly. I came across this situation in a C++ program, and ended up
writing the 'break' as a 'goto' - something like this, but with better
names:
for (int i=0;i<limit;++i)
{
do_stuff();
if (condition) goto for_else;
}
more_stuff();
for_else:
And the comment against the goto said something along the lines of
"this wants to be break-and-a-bit" - it needs to break out of both the
loop and the code that follows it.
"else" isn't the best keyword, but "finally" might give the wrong
impression due to its main use with exceptions. It probably would be a
better choice though.
ChrisA
More information about the Python-ideas
mailing list