Skip to content

Simplify Single Exception Tuple

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: simplify-single-exception-tuple

Section titled “Sourcery refactoring id: simplify-single-exception-tuple”

Replace length-one exception tuple with exception.

try:
read_file()
except (FileNotFoundError,) as e:
log_error(e)
create_file()
try:
read_file()
except FileNotFoundError as e:
log_error(e)
create_file()

Python supports catching multiple exception types at once by using tuples. However, when only a single exception type is being handled, there is no need to wrap it in a tuple.

Using the exception type itself makes your code easier to read, and your intent clearer.