Working around a lack of 'goto' in python

Simon Wittber drconrad at metaplay.com.au
Sun Mar 7 22:52:45 EST 2004


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

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


Roger wrote:
-----------------------
What you have is what many other languages allow with integers after
break or continue statements.  For example you can do 'break 2' or
'continue 3' to break or continue out of the respective number of
enclosing for loops. (Some other languages allow you to label the loops
and then you can name the level in the break/continue statements which
is kind of what you end up doing in C)

Sadly Python doesn't allow numbers. You can write it yourself using
variables to track the looping or throwing exceptions as other posters
have shown, but it can get REALLY complicated if you want to
break/continue out of differing numbers of layers at different points.
It is also quite easy to have bugs due to oversights (been there, done
that :-)

I don't like the rewriting as it greatly complicates the code, and you
are having to write something different than what you mean in your head.
Maybe someone wants to take this on as a PEP?
-----------------------





More information about the Python-list mailing list