Open
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.