Heavily nested code is one of my bigger pet peeves. I’ve found that the more nesting there is in a block of code, the more likely it is that it’ll be confusing to follow. Here’s an example:
def something(request): if condition_a and condition_b and condition_c: lots more and_even_more etc if something_else: etc etc etc etc etc of code here return True else: return False
The “return False” is pretty far-removed from the set of conditions that will cause it to execute. An easy way to restructure this code (while still having the exact same functionality) would be to use the set of conditions as a guard:
def something(request): if not (condition_a and condition_b and condition_c): return False lots more and_even_more etc if something_else: etc etc etc etc etc of code here return True
Preemptive comment: I’m fully aware that some people feel very strongly about only having “single return point” for a function. I disagree. I’d rather minimize the number of return statements from a function, but in this case I think it adds clarity.