Suppose I have a function that does a bunch of work in steps. Between each step I want to either continue or skip the rest of the steps. After the work is done an additional block of code should always be executed. I know that I could use try + finally for that, but it is not really error related and I don't want to throw fake exceptions. The way I do this right now is by abusing an infinite while loop with break statements to achieve some kind of goto. My question is: Is there a more idiomatic way than this?
# ugly goto hack
while True:
do_work()
if condition:
break
do_more_work()
if condition:
break
do_even_more_work()
if condition:
break
#....
break
do_some_final_work()
The simplest option is nested if
statements, reversing the conditions.
do_work()
if not condition:
do_more_work()
if not condition:
do_even_more_work()
if not condition:
# ...
do_some_final_work()
To avoid deep nesting like this, you can use a status variable. We use the following pattern in code that executes a series of steps until some kind of failure happens. This often appears when performing a series of validations.
error = False
# code that executes do_work() and sets error = True if it fails
if not error:
# code that executes do_more_work() and sets error = True if it fails
if not error:
# code that executes do_even_more_work() and sets error = True if it fails
# ...
do_some_final_work()
error
could also be an error message rather than just a boolean.