Limit Your Try Clauses in Python

I am snake

Take this code:

try:
    name = data["parrot"]["name"]
    normalized_name = normalize_name(name)
    parrot = get_parrot(normalized_name)
except KeyError:
    parrot = None

The intention of the try … except statement is catch the potential KeyError from accessing data. However if normalize_name(), get_parrot(), or any function they call use dictionaries, they might also raise ˙KeyError, perhaps due to a bug.

With the code as it is, such errors will be silently ignored. parrot would be set to None, even though name was found, and the program would continue… possibly to destruction!

Instead, we should limit our try clause to the lines that can raise the expected error. Python lets us do this with the else clause:

try:
    name = data["parrot"]["name"]
except KeyError:
    parrot = None
else:
    normalized_name = normalize_name(name)
    parrot = get_parrot(normalized_name)

Simpler and clearer.

This is as per the Handling Exceptions documentation:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

Fin

Hope you try to write better code,

—Adam


Learn how to make your tests run quickly in my book Speed Up Your Django Tests.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: