Good python equivalent to C goto

Matthew Fitzgibbons elessar at nienna.org
Sun Aug 17 23:28:33 EDT 2008


> as mentioned 'in complex code the goto statement is  still the easiest
> to code and understand'.
> The examples are very small and do not require that at all. I agree
> it's ugly.
> Just to show a way to do it.
> 
> A very few functions where I use goto in C or C# are a few hundred
> lines of code, difficult to split in smaller functions.
> A  lot of common data.
> One coming to my mind is a complex validation function for the user
> input of a complex transaction.
> If any test fails, goto the cleaning part and issue error message.
> 
> The goto code is the simpler way to do it.
> We are not talking about simple if-else, but let say 20 if-else.
> Many nested if-else  are more difficult to understand and do not fit
> better the semantics.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

I'm sorry, but if you have any single function that's a few hundred 
lines of code, you need to do some serious refactoring. How do you even 
begin to test that? A goto is just a hack that hides underlying 
problems. If I see a function of more than about twenty lines or having 
more than two or three execution paths, I start thinking of ways to 
break it down.

There are a lot of approaches. Paul Hankin put all the conditionals in a 
helper function. Similarly, you could do something like this (for more 
fun make the validators pluggable):

# each validator is a function that takes the input the be validated
# and returns True for good input; otherwise False
_foo_validators = [_check_this, _check_that, _check_the_other] # etc.

def foo(input):
     for v in _validators:
         if not v(input):
             _on_bad_input(input)
             break
     else:
         _on_good_input(input)
     _on_all_input(input)

Alternatively, you can often turn complex input validation into a state 
machine.

-Matt



More information about the Python-list mailing list