Very Horrible Question About Goto's

Donn Cave donn at u.washington.edu
Wed Apr 19 12:01:59 EDT 2000


Quoth Gaetan Corneau <corg at copernic.com>:
[quoting John Mitchell]
|> 1) the only valid use of goto's in C I've seen looks like this:
|>=20
|> 	if (bogus)
|> 		goto cleanup
|> 	do stuff;
|> 	return(okay);
|> cleanup:
|> 	close file handles;
|> 	do cleanup
|> 	return(error)
|
| There are, at least, two other valid uses:
| 1) the most important: goto's are used a lot by code generators (it
| simplifies writing the generator alot in some cases)
|
| 2) in extreme cases, to improve performances.

Now that we have a list of situations where goto is valid, we are on
the road to realizing that it's just an inherently useful tool.
Which it is.  The cleanup idiom shown above is a common case, but
there are an infinite variety of similar flow of control problems
where goto works out well.

| My own rules are:
| - don't use goto's
|
| if you HAVE to use goto's:
| - don't jump from one function to another (if your language supports =
| it)
| - don't jump backward
|
| I was surprised to learn that Python doesn't have a goto statement.
| Would it be difficult to add?

I wouldn't.  In the abstract, goto is a good thing, but it would be
out of place in Python, whose block constructs, exceptions and so
forth already provide plenty of higher level flow control options.

Here's an idea for a rewrite in Python (for the original poster):
Take your routine and implement it as a class, with the routine local
variables stored in the class instance so you can branch around to
various methods without losing them.  Each class method stores a
final state before it returns, except one method which loops over
the final state value and calls whatever method is appropriate for
that state.  This will be terribly verbose if you have a big mass
of little goto branches that do trivial things, so it will help if
you can cook that down a little first with if blocks etc., and
also identify some block-local variables.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list