Working around a lack of 'goto' in python
rogerb at rogerbinns.com
Sun Mar 7 23:33:38 CET 2004
> Two areas where I've found 'goto' two be useful in other languages are in
> (untested examples in C++)
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