[Python-ideas] Break multiple loop levels
Steven D'Aprano
steve at pearwood.info
Sun May 12 05:44:44 EDT 2019
On Sun, May 12, 2019 at 11:16:21AM +0200, Oleg Broytman wrote:
> On Sun, May 12, 2019 at 01:36:28AM -0700, Elias Tarhini <eltrhn at gmail.com> wrote:
> > If I may propose `break n` as a replacement for the original message's
> > `break break ... break`, where n>0 is the number of contiguous loops to
> > break out of and `break 1` is synonymous with `break`. Seems easier on my
> > eyes/noggin than counting out the individual `break` statements.
>
> This is very much error-prone because on any refactoring (increasing
> or decreasing the number of loop levels) one must increase/decrease all
> numbers in internal loops.
>
> Labels are at least stable.
Indeed.
Go has labels for loops:
Label:
for { ...
break Label
}
as does Rust:
'label: while condition:
{
...
break label
}
We can't use the same syntax in Python, but we might write it like this:
@label while condition:
block
break label
and similar with for loops:
@outer for x in range(100):
@inner for y in range(3):
if x == y == 1: break # like ``break inner``
if x == y == 2: break outer
print(x, y)
# break inner jumps to here
# break outer jumps to here
--
Steven
More information about the Python-ideas
mailing list