[Python-ideas] Break multiple loop levels

David Mertz mertz at gnosis.cx
Sat May 11 22:42:33 EDT 2019


Terry reminds me of a common case I encounter that cannot be transformed
into a loop over itertools.product(). E.g.

for main in stuff:
    if thing_about(main):
        for detail in more_stuff(stuff, main):
            if seen_enough(detail):
                # break to outer somehow
    else:
        for detail in different_stuff():
            if seen_enough(detail):
                # break to outer somehow


On Sat, May 11, 2019, 6:58 PM Terry Reedy <tjreedy at udel.edu> wrote:

> On 5/11/2019 1:20 PM, haael 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 propose two constructions for that:
> >
> > break
> > break break
> > break break break
> > ...
> >
> > continue
> > break continue
> > break break continue
> > ...
> >
> > And so on.
> >
> > Example:
> >
> > for i in range(10):
> >      for j in range(10):
> >          if i == 2 and j == 3:
> >              break break
> >
> > for i in range(10):
> >      for j in range(10):
> >          if i == 2 and j == 3:
> >              break continue
> >          if i == 7:
> >              break break
>
> > Breaking out from many loops at once is a common practice, currently
> > implemented through boolean testing and exceptions.
>
> Python exceptions generalize both 'return' and 'break' as methods for
> escaping nested contexts and are intended for generalized flow control.
>
> > This proposal would make it cleaner.
>
> I actually think that the general method is 'cleaner', be separating
> 'leave here' and 'arrive here'.  This proposal would mean typing fewer
> words in the special case where there are nested loops within one function.
>
> The cost is a) more syntax to learn and b) tightly tying together the
> two loops more tightly than might be necessary, and thereby inhibiting
> re-factoring.  In the examples above, where the loops are inherently
> tied together, the two loops can, as noted by others, be reduced to one.
>   If they are not inherently tied together, one might want to reduce the
> inner loop to a comprehension or wrap it in a new function so it can
> also be used elsewhere.  If the inner loop raises, wrapping or
> unwrapping it, as needed for reusability or efficiency, does not affect
> the logic.
>
> --
> Terry Jan Reedy
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190511/d751582c/attachment-0001.html>


More information about the Python-ideas mailing list