Closed
Description
There is a known idiom for ensuring exhaustiveness of an if
chain:
python/mypy#5818
from typing import NoReturn
def assert_never(x: NoReturn) -> NoReturn:
raise AssertionError(f"Invalid value: {x!r}")
from typing import Union
def type_checking_ok(foo: Union[str, int]) -> None:
if isinstance(foo, str):
print("str")
elif isinstance(foo, int):
print("int")
else:
assert_never(foo)
def type_checking_ko(foo: Union[str, int]) -> None:
if isinstance(foo, str):
print("str")
else:
assert_never(foo)
It works with mypy but I have not tested it with other type checkers.
Because it is not in the standard library, it has to be implemented or imported in many projects that use typing. At my workplace, we have this util under the name assert_exhaustivity
It would be helpful to document this idiom and have it in the standard library. Would a pull request to this repository be the right way to make it happen? Or does it need a PEP?