"Goto" statement in Python

Rob Gaddi rgaddi at highlandtechnology.invalid
Thu Apr 13 13:35:53 EDT 2017

On 04/13/2017 08:26 AM, Marko Rauhamaa wrote:
> Chris Angelico <rosuav at gmail.com>:
>> 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.
> I have occasionally felt the urge to try "goto" in my C code, but having
> written it, I have taken it out. It just doesn't make the code look more
> elegant or robust. Unlike "break" or "return," "goto" makes me uneasy
> about variable scope and lifetime.
> Maybe it would work in some state machine implementation. Some 30 years
> ago I wrote a compiler. The parser came out nicer with methodical use of
> "goto," but even then, I used a parsing-specific macro to wrap it.
> Marko

You see it all the time in kernel code or when doing I/O.  A pretty 
common pattern is:

   int return_val = 1;
   if (init_thing(x)) goto bk1;
   if (init_thing(y)) goto bk2;
   if (init_thing(z)) goto bk3;

   do_things_with(x, y, z);
   return_val = 0;

   bk3:  cleanup_thing(z);
   bk2:  cleanup_thing(y);
   bk1:  cleanup_thing(x);
   return return_val;

But the point is, in Python we have context managers and exceptions and 
classes, all of which serve to allow you to not have to explicitly lay 
out how to wind yourself step-by-step back out of the situation you've 
gotten yourself into.

Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.

More information about the Python-list mailing list