Working around a lack of 'goto' in python

Stephen Horne steve at ninereeds.fsnet.co.uk
Sun Mar 7 19:35:50 CET 2004


On Sat, 06 Mar 2004 18:18:28 GMT, "Brett" <abc at def.net> wrote:

>Two areas where I've found 'goto' two be useful in other languages are in
>(untested examples in C++)
>
>(1) deeply nested loops
>
>for (k=0; k < 10; ++k)
>for (j=0; j < 10; ++j)
>for (i=0; i <10; ++i)
>    if (/* some test */) goto END;
>
>END: /* continue */;
>
>and (2) repeating a while or for loop from the beginning:
>
>BEGIN:
>for (n=0; n < 20; ++n)
>    if (/* some test */) goto BEGIN;
>
>What are the techniques in python for simulating these algorithms without a
>'goto' command?

I've been using C++ quite a while and never needed either of those
patterns. I have used a goto in C++ not too long ago, but not for
anything close to your examples, and its my first time in any language
for at least 10 years.

The reason for it was what I call a 'short running state machine' - a
state machine which needs to run to completion when invoked. I could
have used a loop with an embedded switch statement, but that just
didn't fit what was happening and would have made the code less
readable and maintainable - a goto is the natural representation of a
transition between states.

Once in ten years of doing a lot of programming. I don't think many
people need to worry about this use case ;-)

The normal reason for needing to exit deep loops (or any deep set of
structures), and a common reason for using goto in C, is due to an
error condition. In that case, throw an exception. This is a much
better way to handle errors as the code that throws the exception
doesn't need to know how (or if) the exception will be handled.

The only other common case where I've seen C's goto considered a good
thing is in search algorithms. The easy exit from the (probably
nested) loops can be useful. But when doing searches I tend to regard
success as the exceptional case and throw an exception for it, though
I don't think I've used the technique in Python to date. 


If you have a use case for the loop restarting, I'd like to see it.
With a use case it is much easier to provide an alternative, and there
isn't any that strikes me as obvious as it stands.


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk



More information about the Python-list mailing list