"Goto" statement in Python

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

On 13/04/2017 15:35, Chris Angelico wrote:
> On Thu, Apr 13, 2017 at 9:31 PM, alister <alister.ware at ntlworld.com> wrote:
>> I expect you could simulate most of these with a custom exception
>> for example break from nested loop:
>> class GoTo(Exception):
>>     pass
>> try:
>>     for i in range(100):
>>         print i
>>         for j in range (50):
>>             print j
>>             if i*j>60:
>>                 raise GoTo
>> except GoTo:
>>     print "Exit Early"
>> print "end of loop"
> Or you could turn it into a function and "return". Or if you feel like
> it, you could turn the nested loops into a generator, then iterate
> over it and break when you need to.

I know this isn't the Python need-for-speed thread, but this is a 
classic example where the lack of one simple feature leads to using 
slower, more cumbersome ones.

'goto' would be one easy-to-execute byte-code; no variables, objects or 
types to worry about. If implemented properly (with the byte-code 
compiler using a dedicated name-space for labels) there would be no name 

Function calls, returns and generators are rather more heavyweight in 

  There are many things you CAN do,
> but to the true goto-aficionado, none of them is as clean.
> 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.


More information about the Python-list mailing list