Python: Do not report unreachable "catch-all" cases in elif-chains.

This was brought up on the LGTM.com forums here:
https://discuss.lgtm.com/t/warn-when-always-failing-assert-is-reachable-rather-than-unreachable/2436

Essentially, in a complex chain of `elif` statements, like

```python
if x < 0:
    ...
elif x >= 0:
    ...
else:
    ...
```

the `else` clause is redundant, since the preceding conditions completely
exhaust the possible values for `x` (assuming `x` is an integer). Rather than
promoting the final `elif` clause to an `else` clause, it is common to instead
raise an explicit exception in the `else` clause. During execution, this
exception will never actually be raised, but its presence indicates that the
preceding conditions are intended to cover all possible cases.

I think it's a fair point. This is a clear instance where the alert, even if it
is technically correct, is not useful for the end user.

Also, I decided to make the exclusion fairly restrictive: it only applies if
the unreachable statement is an `assert False, ...` or `raise ...`, and only
if said statement is the first in the `else` block. Any other statements will
still be reported.
This commit is contained in:
Taus Brock-Nannestad
2019-10-29 12:03:41 +01:00
parent 6e6dab9ab8
commit 5e62da7690
2 changed files with 30 additions and 7 deletions

View File

@@ -120,3 +120,20 @@ def foo(x):
print(x, "== 0")
# Unreachable catch-all case
def unreachable_catch_all_assert_false(x):
if x < 0:
return "negative"
elif x >= 0:
return "positive"
else:
assert False, x
def unreachable_catch_all_raise(x):
if x < 0:
pass
elif x >= 0:
pass
else:
raise ValueError(x)