Another idea that came up in a few recent threads is a `typing.assert_never()` function, which indicates that some code is supposed to be unreachable. I will submit an implementation to CPython, and we can use this thread to work out any details (or to let me know that we shouldn't do this after all).
# Specification
We will add a new function `typing.assert_never()` with the following signature:
def assert_never(arg: NoReturn, /) -> NoReturn: ...
At runtime, this will unconditionally raise `RuntimeError(f"Unexpectedly reached {arg!r}")` (wording suggestions welcome).
Type checkers should emit an error if the function is called with an argument that has a non-bottom type. Examples:
match bool():
case True: pass
case False: pass
case _ as x: assert_never(x) # ok
match int():
case 0: pass
case 1: pass
case _ as x: assert_never(x) # error: x is an int, not NoReturn
# Motivation
PEP 484 only allows NoReturn as a return type, but in practice all type checkers allow it in argument positions as a bottom type. Thus, a manually defined `assert_never()` function already has the behavior specified above. Adding the function to the standard library will make this behavior more discoverable for users.
# Open questions
Suggestions welcome for better wording in the runtime error.
There is a related proposal to rename NoReturn to Never. I'm lukewarm about that because renaming things always causes churn, but in any case let's discuss that separately.