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@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to