Working around a lack of 'goto' in python

Roger Binns rogerb at rogerbinns.com
Mon Mar 8 15:43:11 EST 2004


> Well, say you decide that several lines of code should be executed
> repeatedly.  You can stick in the while...: , your editor can indent
> the block, then you have to hunt for numbered `continue` and `break` and
> increment some, but not all of the numbers.  Unnumbered `continue` and
> `break` cause similar trouble, but the trouble is guaranteed to be more
> local.  For non-local I much prefer the exit-by-exception.

That is fine (and only solves break - continue is more of a pain, and things
get real ugly if you have both break and continue).  You are not forced to
use every language construct. For example I never use 'else' with for loops.
Similarly to your argument, multiple inheritance can also be error prone
(eg call a different base class than you thought, order of inheritance
matters).  Some languages don't let you use multiple inheritance
ever.  Others (such as Python) realize that it can occassionaly be
useful and allow you to use it.

All general purpose languages let you have looping constructs (for and
while) and usually let you nest them to arbitrary depths (ie it isn't
considered a bad thing by the languages to have nested loops).  They
all let you break out of the loops before they would naturally terminate
(break) and usually do the next iteration of the loop (continue - Modula
2 doesn't have this).

Since nested loops are ok, and break/continue out of one enclosing loop
is ok, why is break/continue out of more than one some sort of great
evil?  Your argument about introducimg more loops in the same code
requiring fixing of the numbers doesn't really matter.  You may have to
do code surgery if you went from one enclosing loop to two (because there
is no break 2/continue 2) so each loop construct has to be examined
anyway.  Python's indentation rules also make it VERY clear what is
going on.  Any code editor can trivially renumber existing code when you
insert a new loop.

Just like multiple-inheritance, this may be of no use to you or
a construct you feel is too dangerous for your code.  That doesn't
mean it should be prevented from others using it.

Several pieces of my code would greatly benefit from break/continue
of multiple depths.  They currently use extra variables and exceptions
and have had a tendency to be somewhat buggy due to the extra complexity
and the mismatch between my mental model and what the language allows.

Roger





More information about the Python-list mailing list