Limit Your Try Clauses in Python2019-10-02
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
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
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
tryclause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the
try … exceptstatement.
If your Django project’s long test runs bore you, my book can help.
One summary email a week, no spam, I pinky promise.
- Tuples versus Lists in Python
- How I Import Python’s datetime Module
- Entering a Flaky Context Manager in Python
© 2019 All rights reserved.