"Goto" statement in Python

bartc bc at freeuk.com
Thu Apr 13 13:17:24 EDT 2017


On 13/04/2017 16:03, Ian Kelly wrote:
> On Thu, Apr 13, 2017 at 8:52 AM, bartc <bc at freeuk.com> wrote:
>> On 13/04/2017 15:35, Chris Angelico wrote:
>>> Personally, I can't remember the last time I yearned for "goto" in
>>> Python, and the only times I've ever wished for it or used it in other
>>> languages have been multi-loop breaks or "for...else" blocks. And
>>> neither is very frequent.
>>
>>
>> It might be a better idea to have a multi-level loop break then. This would
>> also be an absolute jump byte-code.
>
> This has previously been proposed and rejected:
> https://www.python.org/dev/peps/pep-3136/

Poorly presented I think with, what, five possible ways of adding it?

> Rejection notice:
> https://mail.python.org/pipermail/python-3000/2007-July/008663.html

Rejected because it would only occur in complex code? That's just where 
it would help!

I think it should be in for completeness, and to avoid this bug in the 
language; start with:

  for i in range(n):
     break;

break inside a loop; that's currently allowed. Now for reasons of logic, 
that break is put inside an 'if' branch:

  for i in range(n):
     if cond:
        break;

The break still works. But if, for any reason at all, that break ended 
up inside a nested loop instead of a nested if:

  for i in range(n):
     while cond:
        break;

Now it no longer works as expected. The break has been 'captured' by the 
new loop.

(IME most breaks from loops are either from the innermost loop, or from 
the outermost one. For these two cases, you don't need naming, labelling 
or numbering of loops. Just 'break [inner]' or 'break outer'.)

-- 
bartc



More information about the Python-list mailing list