⬅ back to the index
Signaling Intent By Separating Python Blocks With Ambiguous Relationships
The best code isn't just easy to read. It also helps you catch mistakes.
This is not a perfect process. Do your best.
In Python you don't get the benefit of curly braces to indicate the boundaries of a block, so you have to rely on indentation to indicate the effects of a condition. Some people think this is a good thing, but it means that you can accidentally change the meaning of the code by changing the indentation, and it means that a person cannot look at code and know without any doubt what the code is supposed to be doing, and that's definitely bad, so we need to put additional care into formatting our code to alleviate this.
Good blank lines
Consider the following blocks of code:
Original
if a:
b
else:
c
if d:
e
if f:
g
Altered
if a:
b
else:
c
if d:
e
if f:
g
They're identical except someone accidentally hit tab while some lines were selected.
The behaviors are obviously different, but which behavior is correct? You have no way of knowing.
You don't know this code. You don't know the history of why this code was written in the first place. You don't know the decisions that went into making this code the way it is. You don't know which of the code is intentional and which of the code is just a simple mistake.
But what if the original code had signaled intent?
if a:
b
else:
c
if d:
e
if f:
g
It's a small difference, but now you don't have to guess which lines are supposed to be part of which scope. You can see that the three ifs are meant to be at the same scope with each other. The distance between correct behavior and undetectably incorrect behavior has increased from one accidental edit to more than one.
It's not a perfect signal, of course, because nothing stops people from putting blank lines where they aren't needed, but at least if the indentation changes accidentally like
if a:
b
else:
c
if d:
e
You can then say "Wait! The blank line there means I need to look more closely at what this is doing. There might be a mistake here." And that's a very useful signal.
Bad blank lines
Don't do this:
if a:
b
else:
c
There's no logical separation between the if and the else in a condition, they're necessarily connected to each other, so splitting them apart increases confusion instead of reducing it.