Good python equivalent to C goto

Michael Torrie torriem at
Sun Aug 17 06:35:31 CEST 2008

Dennis Lee Bieber wrote:
> 	Nasty code even for C... I've never used goto in C... Options:
> convert the statements of next into a function, and put in an else
> clause...

I think the parent post's pseudocode example was too simple to show the
real benefits and use cases of goto in C.  Obviously his simple example
was contrived and could easily be solved with proper if tests.  Your
idea of using a function is correct for python, though, but not for C

However, what you say about else clauses gets extremely hairy when you
have to deal with multiple nested if statements.  The most common use
case in C for goto is when you have cleanup code that must run before
leaving a function.  Since any number of things could happen while
processing a function (at any level of the if statement) that would
trigger an exit, having a whole bunch of else statements gets very, very
tedious and messy.  Often involves a lot of code duplication too.  Goto
is direct and much cleaner and more readable.

A function in C wouldn't work for this because of scoping rules.

However it's not necessary in python to do any of this, since you can
define nested functions that have access to the parent scope.  Anytime
you need to clean up, just call the nested cleanup function and then return.

More information about the Python-list mailing list