Simplify Your If Statements That Return Booleans2020-01-17
Here’s a hint I have found myself repeating in code review. I learnt this from my university lecturer Tony Field, who probably repeated it in every lecture! He was teaching us Haskell, but it applies to Python, and most other programming languages.
Take a look at this code:
While clear and correct, it’s longer than it needs to be. The function body can be simplified - down to one line!
if takes a boolean expression - a Python
Here the expression is
widget.frobnications >= 12.
Our code then returns a
True if the expression is
False if the expression is
We can remove this redundant redundancy by returning the expression instead:
(The brackets are not necessary in Python, but I like keeping them for clarity.)
In general, any expression of the form:
…can be simplified to:
The wrapping call to
bool is unnecessary if the expression already returns a
This at least all comparison and boolean operators (
If you’re not returning but instead assigning a new variable:
…this can also be simplified to:
In general, that means code looking like:
…can be simplified to:
One Line Format
Python also has the single line
if format, for example:
…this can be simplified as above:
If you’re returning the negation of an expression (reversed
…this can be simplified using
You might be able to simplify further by swapping to the opposite operator(s) and removing the
For example here
>= can be swapped to
If you’re also doing something on one path only, you can simplify with this pattern too. For example, if we wanted log a message when encountering unfrazzable widgets:
We can separate it by storing the boolean result in a variable and returning it after logging:
This is one line shorter, and also has the advantage of a single
return at the end of the function.
Hope this helps you write clearer code! If I sent you this article in code review, thanks for taking the time to read.
Working on a Django project? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
- Limit Your Try Clauses in Python
- How I Import Python's datetime Module
- Tuples versus Lists in Python
© 2021 All rights reserved.