What sorts of methods exist for prematurely exiting an if
clause?
There are times when I'm writing code and want to put a break
statement inside of an if
clause, only to remember that those can only be used for loops.
Lets take the following code as an example:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
...
if condition_b:
# do something
# and then exit the outer if block
# more code here
I can think of one way to do this: assuming the exit cases happen within nested if statements, wrap the remaining code in a big else block. Example:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
else:
...
if condition_b:
# do something
# and then exit the outer if block
else:
# more code here
The problem with this is that more exit locations mean more nesting/indented code.
Alternatively, I could write my code to have the if
clauses be as small as possible and not require any exits.
Does anyone know of a good/better way to exit an if
clause?
If there are any associated else-if and else clauses, I figure that exiting would skip over them.
(This method works for if
s, multiple nested loops and other constructs that you can't break
from easily.)
Wrap the code in its own function. Instead of break
, use return
.
Example:
def some_function():
if condition_a:
# do something and return early
...
return
...
if condition_b:
# do something else and return early
...
return
...
return
if outer_condition:
...
some_function()
...