Detect unreachable `except` branches
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Since except blocks are checked in order, and the first matching block is executed, it's possible to accidentally write a try-except that will never execute some branches. For example:
def bad_reader(path: str) -> bytes:
if path == "bad":
raise PermissionError
with open(path, "rb") as f:
return f.read()
def load_data(path: str) -> bytes:
try:
return bad_reader(path)
except OSError:
print("OSError caught")
except PermissionError:
# This branch will never be hit, since `OSError` will always catch
# permission error
print("PermissionError caught")
return b""
load_data("bad")
Since PermissionError is a subclass of OSError, the except PermissionError case will never execute. I'd expect/hope that these kind of mistakes would be detectable with type information. I think adding checks for this would make sense under the --warn-unreachable config flag, so a new CLI option may not be needed.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue identifies the existing --warn-unreachable configuration as the intended entry point. Investigate how mypy checks exception types and define completion as reporting a later handler subsumed by an earlier handler, with coverage for the PermissionError/OSError ordering example.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100