I want to share some more info that I’ve found on this because I think it will contribute to the exhaustiveness of the information in this thread.
First the python typing documentation has a specific section about this question of “exhaustiveness checking”: Unreachable Code and Exhaustiveness Checking — typing documentation.
Next, consider this real-life function from the library I linked above.
def get_pdg_round_digit(num: Decimal):
top_digit = get_top_digit(num)
# Bring num to be between 100 and 1000.
num_top_three_digs = num * 10 ** (2 - top_digit)
num_top_three_digs = round(num_top_three_digs, 0)
new_top_digit = get_top_digit(num_top_three_digs)
num_top_three_digs = num_top_three_digs * 10 ** (2 - new_top_digit)
if 100 <= num_top_three_digs <= 354:
round_digit = top_digit - 1
elif 355 <= num_top_three_digs <= 949:
round_digit = top_digit
elif 950 <= num_top_three_digs <= 999:
round_digit = top_digit
else:
raise ValueError
return round_digit
In this case, assuming the math is done right and get_top_digit works as expected, then num_top_three_digits will always be a number between 100 and 999. there is not even any user input that could be passed in to hit the ValueError. That code is truly unreachable. What should be done for this sort of code? I think the exhaustiveness checking doc above would recommend
...
else:
assert False, "unreachable"
And this feels appropriate to me.
One final note. This came up in the context of trying to write test for these “unreachable” lines of code. For code that can be reached with mistaken user input the test is easy to write with assertRaises. But a line of code like I’ve shown above just can’t be tested I don’t think.
I’m using the coverage package to do test coverage. the docs indicate that lines like this can be excluded from test coverage calculations with a comment:
...
else: # pragma: no cover
assert False, "unreachable"