Skip to content

Exhaustiveness checking with pytype #1076

@theahura

Description

@theahura

In mypy there is a technique to implement exhaustiveness checking using the NoReturn type. The short version is that you can create a 'magic' function like so:

def assert_never(value: NoReturn) -> NoReturn:
    assert False, f'Unhandled value: {value} ({type(value).__name__})'

and then call the magic function in an if block, e.g.:

from typing import Union

def get_float(num: Union[str, float]) -> float:
    if isinstance(num, str):
        return float(num)
    else:
        assert_never(num)

will throw a compile time error because it does not check the float type, while

def get_float(num: Union[str, float]) -> float:
    if isinstance(num, str):
        return float(num)

    elif isinstance(num, float):
        return num

    else:
        assert_never(num)

will not.

Does pytype support an equivalent?

See also: python/mypy#5818

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions