Working around a lack of 'goto' in python

Roger Binns rogerb at rogerbinns.com
Mon Mar 8 01:24:43 EST 2004


> This has to be the worst idea I've seen in a long time.

Well, it is popular enough to be in shell scripting (digit
form), several forms of Basic (either form), another poster
mentioned ADA, and I have seen it in other languages which
I have forgotten.

Note that your mental model is one of "I want to continue/break
*that* loop".  When *that* is the enclosing loop, break/continue
is easy.  When it is outside the enclosing loop, you then have
to figure out how to transfer control to the appropriate
location using exceptions, state variables and who knows
what else.

> Breaking out of multiple nested loops of various depths is actually very
> simple. Raise an exception, and catch it outside the loop.

That works in the trivial case.  It gets way more complicated
if there are multiple locations you want to do the 'break 2' and
'continue 2' from (and exceptions pretty much only cover the 'break'
case anyway without even more work).

Here is an example of code using break/continue with numbers.  Try it
using exceptions.  Note that this form of code is fairly common
when doing parsing/interpretting of files and building up
data structures (ie same place you tend to see gotos in C)

for l1 in loop1:
   do stuff
   while loop2:
      do other stuff
      for l3 in loop3:
          do more stuff
          if blah blah:
             break 2
          if foo bar:
             continue 3
          do stuff harder
      if orange:
          continue 2
      do stuff hardest

Roger





More information about the Python-list mailing list