Merge Exception Handlers
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: merge-except-handler
Section titled “Sourcery refactoring id: merge-except-handler”Description
Section titled “Description”Merge exception handlers with the same body into a single except handler.
Before
Section titled “Before”try: f = open("myfile.txt") s = f.readline() i = int(s.strip())except OSError as err: logger.exception("Error while reading myfile.txt") raiseexcept ValueError as err: logger.exception("Error while reading myfile.txt") raisetry: f = open("myfile.txt") s = f.readline() i = int(s.strip())except (OSError, ValueError) as err: logger.exception("Error while reading myfile.txt") raiseExplanation
Section titled “Explanation”By merging except handlers with the same body we remove duplicate code. This makes it easier to read, and when changing the logic we won’t accidentally change it in only one place instead of both.
Related Rules
Section titled “Related Rules”- remove-redundant-except-handler to
remove unreachable
exceptblocks - remove-redundant-exception to clean up the tuple of an except clause
- use-contextlib-suppress instead of empty
exceptblocks - do-not-use-bare-except to always specify which
errors an
exceptblock is handling