ty
ty copied to clipboard
Warn on (accidentally) unreachable code blocks
Mypy and pyright both offer opt-in lints which, when enabled, cause them to complain about the else branch in this snippet:
def f(x: int | str):
if isinstance(x, int):
print("It's an int")
elif isinstance(x, str):
print("It's a string")
else:
print("It's something else")
They can both detect that the else branch is unreachable, and that this is probably an accident, indicating a logic error somewhere in the function. Mypy's version can be opted into using --warn-unreachable on the command line; pyright's version requires reportUnreachable=true.
For feature parity with these tools, we should aim to provide a similar lint.
Note that the lint should only complain about accidentally unreachable code. There's a lot of code that ty infers as being unreachable that is nonetheless deliberately unreachable, which we should not complain about:
- Any unreachable branches that consist solely of a
raisestatement should not be reported - Any unreachable branches that consist solely of an
assert_never()call should not be reported - Any branches that are unreachable due to a
sys.version_info,sys.platform, orif TYPE_CHECKINGcheck should not be reported