Unnecessary else statements

Share
Copied to clipboard.
Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
3 min. read 2 min. video Python 3.8—3.12

Let's talk about unnecessary else statements in Python.

A function where both if and else return

This earliest_date function uses the python-dateutil third-party library to parse two strings as dates:

from dateutil.parser import parse


def earliest_date(date1, date2):
    """Return the string representing the earliest date."""
    if parse(date1, fuzzy=True) < parse(date2, fuzzy=True):
        return date1
    else:
        return date2

This function returns the string which represents the earliest given date:

>>> earliest_date("May 3 2024", "June 5 2025")
'May 3 2024'
>>> earliest_date("Feb 3 2026", "June 5 2025")
'June 5 2025'

Note that this function uses an if statement that returns, and an else that also returns.

Is that else statement unnecessary?

We don't necessarily need that else! We could delete it and simply return from our function:

from dateutil.parser import parse


def earliest_date(date1, date2):
    """Return the string representing the earliest date."""
    if parse(date1, fuzzy=True) < parse(date2, fuzzy=True):
        return date1
    return date2

But should we? Which way is better?

Sometimes else improves readability

I would actually prefer to leave this else statement in! Why?

Well, neither of these returns is really more important than the other:

from dateutil.parser import parse


def earliest_date(date1, date2):
    """Return the string representing the earliest date."""
    if parse(date1, fuzzy=True) < parse(date2, fuzzy=True):
        return date1
    else:
        return date2

We're checking whether one date is less than the other. If it is, we return that date, otherwise we return the other date.

If we remove the else, it kind of looks like one date is somehow more important (or at least different) than the other:

from dateutil.parser import parse


def earliest_date(date1, date2):
    """Return the string representing the earliest date."""
    if parse(date1, fuzzy=True) < parse(date2, fuzzy=True):
        return date1
    return date2

It looks like the code inside the if block is an exceptional case, and the code outside is the usual case. But it's not!

With the else, this code looks to me a bit like a balance scale, with an if and an else on either side.

Balance scale showing "if" and "else" on each side

If we removed the else statement, the code would look lopsided. I don't think that would make it more readable.

But there are times that I do prefer to remove an unnecessary else at the end of a function.

When should you remove an else statement?

Here's a function that calculates the size of a directory:

from pathlib import Path

def calculate_directory_size(path):
    path = Path(path)
    if path.is_file():
        return path.stat().st_size
    else:
        return sum(
            calculate_directory_size(item)
            for item in path.iterdir()
        )

First we check whether the given path is a file. If it is, we simply return its size.

Otherwise, we loop over all the paths in the given directory (using recursion) and we sum up their sizes.

>>> calculate_directory_size("/home/trey/Downloads")
1548944172

I would prefer to remove the else in this code because this feels like the most important part of this function:

    else:
        return sum(
            calculate_directory_size(item)
            for item in path.iterdir()
        )

The code inside the if block is simply a check at the beginning to see whether we've hit a base case, the easy case:

    if path.is_file():
        return path.stat().st_size

I would rather remove the else in cases like this.

from pathlib import Path

def calculate_directory_size(path):
    path = Path(path)
    if path.is_file():
        return path.stat().st_size
    return sum(
        calculate_directory_size(item)
        for item in path.iterdir()
    )

Even though we were returning in both the if and the else, the body of the if and the body of the else didn't feel balanced to begin with.

Considering readability with if-else statements

So the next time you find an if-else in your code where both the if and the else return from the function that you're in, you could think of that else as unnecessary. But that doesn't necessarily mean it's completely unhelpful.

So before you remove that else statement, think about whether it makes your code more readable or not.

Series: Conditionals

Conditionals statements (if statements) are useful for making a branch in our Python code. If a particular condition is met, we run one block of code, and if not then we run another block.

To track your progress on this Python Morsels topic trail, sign in or sign up.

0%
A Python Tip Every Week

Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.