[Python-ideas] Break multiple loop levels

Jonathan Goble jcgoble3 at gmail.com
Sat May 11 18:34:24 EDT 2019


On Sat, May 11, 2019 at 1:22 PM haael <haael at interia.pl> wrote:
> Python allows for breaking out from a loop through 'break' and
> 'continue' keywords. It would be nice if it was possible to break many
> loop levels using one command.

I'm surprised no one has yet mentioned splitting off the loops into a
function and using "return" to break out of those loops. If you nest
the function in the spot where the loops would be and use nonlocal
statements, you can even modify variables in the surrounding code
(counters, etc.) or leave values behind.

If you're opposed to a function and performance is not critical [1],
you can also raise a custom "exception" at the multi-break spot and
handle it at the appropriate place in the outer code. This is useful
if you need to break out of a function plus additional nesting layers.

[1] I mention performance here because if I recall correctly,
exception handling is quite expensive and slow in Python.


More information about the Python-ideas mailing list