Sub topic 12
Flattening logic with guard clauses
This chapter assumes you can write if/elif/else, use and/or/not, and define functions that return values. It covers how to replace deeply nested conditionals with guard clauses.
The problem with deep nesting
Nested conditionals push the main logic further right with every level. Readers must track several open conditions at once to know when the real work happens.
def shipping_cost(weight):
if weight > 0:
if weight <= 1:
return 5
else:
if weight <= 5:
return 10
else:
return 20
else:
raise ValueError('weight must be positive')This works, but the error case sits at the bottom, far from the check that triggers it. Each else adds another level of indentation.
What a guard clause is
A guard clause is an if at the top of a function that handles an invalid or simple case and exits at once. The exit is a return, a raise, or, inside a loop, continue or break. After the guard, the rest of the function can assume the condition is false.
def shipping_cost(weight):
if weight <= 0:
raise ValueError('weight must be positive')
if weight <= 1:
return 5
if weight <= 5:
return 10
return 20The behavior is the same, and the code is flat. Each if has no else because the return or raise already ends the function. Reading top to bottom, you meet the rejected inputs first and the normal path last.
Refactoring step by step
Take a function that nests its conditions.
def process(order):
if order is not None:
if order['items']:
if order['paid']:
return 'shipped'
else:
return 'awaiting payment'
else:
return 'empty order'
else:
return 'no order'Follow these steps:
- Find the innermost "happy path", here
return 'shipped'. - Invert each outer condition and handle it first with an early return.
- Remove the
elsethat each early return makes unnecessary.
def process(order):
if order is None:
return 'no order'
if not order['items']:
return 'empty order'
if not order['paid']:
return 'awaiting payment'
return 'shipped'The order of guards matters. The None check comes first because order['items'] would fail on None. Each guard protects the lines below it.
Guards inside loops
In a loop, continue works as a guard that skips an item.
readings = [12, None, -3, 25, 40]
for value in readings:
if value is None:
continue
if value < 0:
continue
print(value)This prints 12, 25, and 40.
When not to use guards
Guard clauses are not always better. If both branches are equally important and neither is an error or special case, a plain if/else states that symmetry more clearly.
def label(n):
if n % 2 == 0:
return 'even'
else:
return 'odd'Also avoid a long run of guards that all do unrelated work. If a function needs ten guards, it probably does too much and should be split.
Exercise
Rewrite this function using guard clauses and no else.
def discount(age, member):
if age >= 0:
if member:
return 0.2
else:
if age >= 65:
return 0.1
else:
return 0
else:
raise ValueError('age cannot be negative')
Show answer
def discount(age, member): if age < 0: raise ValueError('age cannot be negative') if member: return 0.2 if age >= 65: return 0.1 return 0
Exercise
In the guard-clause version of process(order), what happens if you move the if not order['items'] check above the if order is None check, and order is None?
Show answer
Python raises a TypeError, because it tries to index None with ['items']. The None guard must come first so later guards can assume order is a dictionary.