Sub topic 12
Flattening logic with guard clauses
Earlier chapters showed if, elif, and else building decision chains. This chapter covers a way to arrange those chains so that functions stay flat and easy to read. It assumes you can write functions with return, you know raise and ValueError, and you are comfortable with truthiness and is None tests.
The problem: the pyramid of nested ifs
Nested conditionals work, but each new requirement pushes the main logic further to the right. Here is a function that decides what to do with an order:
def ship_order(order):
if order is not None:
if order["items"]:
if order["paid"]:
return "shipped"
else:
return "awaiting payment"
else:
return "empty order"
else:
raise ValueError("order is required")
print(ship_order({"items": ["book"], "paid": True}))
print(ship_order({"items": [], "paid": True}))
print(ship_order({"items": ["book"], "paid": False}))The output is shipped, empty order, and awaiting payment. The function is correct, but the happy path (return "shipped") is buried three levels deep. Each else sits far from the if it belongs to, so you have to count indentation to match them.
The fix: guard clauses
A guard clause is an if that checks for a bad or special case at the top of a function and exits immediately, usually with return or raise. After all the guards, the rest of the function can assume the input is acceptable.
def ship_order(order):
if order is None:
raise ValueError("order is required")
if not order["items"]:
return "empty order"
if not order["paid"]:
return "awaiting payment"
return "shipped"
print(ship_order({"items": ["book"], "paid": True}))
print(ship_order({"items": [], "paid": True}))
print(ship_order({"items": ["book"], "paid": False}))The behavior is identical. The structure differs in three ways:
- Nothing is nested. Every statement sits at the same indentation level.
- No
elseis needed, because theifbody always exits. If the body ran, the code below it never runs. - The last line is the normal outcome. Each line above it names one reason the normal outcome does not apply.
Why the `else` can be dropped
An else after a block that ends in return, raise, continue, or break is redundant. Control cannot fall out of that block into the code after it. These two functions are equivalent:
def sign_with_else(n):
if n < 0:
return "negative"
else:
return "non-negative"
def sign_without_else(n):
if n < 0:
return "negative"
return "non-negative"
print(sign_with_else(-2), sign_without_else(-2))
print(sign_with_else(5), sign_without_else(5))Linters such as pylint report the first form as no-else-return. The same applies to an elif that follows a block ending in return. Whether you remove the else is a style choice. The rule is that the shorter form is fine when the early exit is obvious, and the explicit else is fine when two branches are equal alternatives.
Guards inside loops
Inside a loop, the early exits are continue (skip this item) and break (stop the loop). They flatten loop bodies the same way return flattens functions.
def total_valid(readings):
total = 0
for reading in readings:
if reading is None:
continue
if reading < 0:
continue
total += reading
return total
print(total_valid([3, None, -1, 4]))This prints 7. The None check must come before the < 0 check. Comparing None < 0 raises TypeError, so the first guard protects the second.
The two continue guards could be merged with or:
def total_valid(readings):
total = 0
for reading in readings:
if reading is None or reading < 0:
continue
total += reading
return totalThis works because of short-circuit evaluation: when reading is None is true, the right side is never evaluated. Use separate guards when the reasons differ and you want to log or handle them separately. Merge them when the reason is the same.
Ordering guards
Guards run top to bottom, so order matters in three ways.
- Validity before use. A guard that looks inside a value must come after the guard that checks the value exists. Checking
len(name)beforename is Nonefails onNone. - Errors before special cases. Reject invalid input first, then handle unusual-but-valid input, then fall through to the general case. This is how the
shipping_costfunction from the topic plan is arranged:
def shipping_cost(weight):
if weight <= 0:
raise ValueError("weight must be positive")
if weight <= 1:
return 5
if weight <= 5:
return 10
return 20
for w in (0.5, 3, 8):
print(w, shipping_cost(w))The output is 5, 10, and 20. Note that weight <= 5 does not need to say 1 < weight <= 5. The earlier guard already returned for every weight at or below 1, so reaching the second guard implies weight > 1. This is the same top-to-bottom logic that makes elif chains work.
- Cheap checks before expensive ones. If one guard requires a database call and another compares two integers, put the integer comparison first.
When a guard clause is the wrong tool
Guards express "this is an exception to the normal path." They fit poorly when both branches are equally normal.
def describe_temperature(celsius):
if celsius >= 25:
return "warm"
else:
return "cool"Here neither case is an exception, so the if/else reads naturally. Rewriting it with a guard gains nothing.
| Situation | Better choice |
|---|---|
| Invalid input that should stop the function | Guard clause with `raise` |
| An empty or trivial case with an immediate answer | Guard clause with `return` |
| Skipping bad items in a loop | Guard clause with `continue` |
| Two equal alternatives | `if`/`else` |
| Many values of one variable mapped to results | `elif` chain or `match` |
| Choosing between two values for an assignment | Conditional expression |
Gotchas
A missing final return gives you None
Guards often return early, and it is easy to forget the case that reaches the bottom. A function that ends without return returns None.
def classify(n):
if n < 0:
return "negative"
if n > 0:
return "positive"
print(classify(0))This prints None, because no guard covers zero. Always end a guarded function with a final return or raise for the default case.
Cleanup code can be skipped
An early return skips every statement below it. If the function opens a resource and later closes it with a plain statement, a guard in between leaves the resource open. Use with or try/finally so cleanup runs on every exit path.
def first_line(path):
if not path:
raise ValueError("path is required")
with open(path) as handle:
return handle.readline()The guard runs before the file is opened, so there is nothing to clean up. The with block closes the file even though the function returns from inside it.
Too many exits
A function with a dozen guards and a dozen return statements is hard to follow in a different way. Flat is better than nested, but a long list of guards often means the function does too much. Consider splitting validation into its own function and calling it first.
Summary of the technique
- Identify the normal outcome of the function.
- List the conditions under which that outcome does not apply.
- Write one
iffor each condition at the top, ordered by validity, then special cases, then cost. - End each guard body with
return,raise,continue, orbreak. - Put the normal outcome last, at the base indentation level.
Exercise
Rewrite this function with guard clauses so it has no nested if statements and no else. Keep the same behavior.
def discount(user, total):
if user is not None:
if total > 0:
if user["member"]:
return total * 0.9
else:
return total
else:
raise ValueError("total must be positive")
else:
raise ValueError("user is required")
Show answer
Check the failure cases first, then return the normal results. For example: if user is None: raise ValueError("user is required"), then if total <= 0: raise ValueError("total must be positive"), then if user["member"]: return total * 0.9, then return total. The user is None guard must come before any use of user. The order of the two raise guards does not change the results for valid inputs, but it decides which error is reported when both problems are present.
Exercise
What does this function return for values = [4, None, 9], and why? Fix the bug.
def largest(values):
best = 0
for v in values:
if v > best:
best = v
return best
Show answer
It raises TypeError when it compares None > 0. Add a guard at the top of the loop body: if v is None: continue. It must come before the comparison. With the guard, the function returns 9. Separately, starting best at 0 gives a wrong answer for lists of only negative numbers, so a stronger version starts with best = None and guards with if best is None or v > best.