Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exhaustiveness Research #4

Closed
johnthagen opened this issue Apr 18, 2022 · 3 comments
Closed

Exhaustiveness Research #4

johnthagen opened this issue Apr 18, 2022 · 3 comments
Labels

Comments

@johnthagen
Copy link
Owner Author

I ran into an issue testing mypy. assert_never() is quite young (only a month or so old) so there could be some bugs:

@johnthagen
Copy link
Owner Author

johnthagen commented Apr 18, 2022

Here is an example that works in the Python 3.10 and current mypy that can be used to play around with exhaustiveness checking.

from enum import Enum, auto

from typing_extensions import NoReturn


# TODO: Remove the need for this when mypy > 0.942 is released.
#     At that point, simply import this from `typing_extensions`
def assert_never(__arg: NoReturn) -> NoReturn:
    raise AssertionError("Expected code to be unreachable")


class Color(Enum):
    Red = auto()
    Green = auto()
    Blue = auto()


def c(color: Color) -> int:
    match color:
        case Color.Red:
            pass
        case Color.Blue:
            pass
        case _ as u:
            assert_never(u)


def int_or_str(arg: int | str) -> None:
    match arg:
        case int():
            print("It's an int")
        case str():
            print("It's a str")
        case _ as unreachable:
            assert_never(unreachable)

@johnthagen
Copy link
Owner Author

johnthagen commented Apr 18, 2022

While exhaustiveness checking does not work currently on the proposed base-class method without @sealed, it does work with the existing Union method:

from dataclasses import dataclass
from enum import Enum, auto

# TODO: Remove the need for this when mypy > 0.942 is released.
#     At that point, simply import this from `typing_extensions`
def assert_never(__arg: NoReturn) -> NoReturn:
    raise AssertionError("Expected code to be unreachable")


class UsState(Enum):
    Alabama = auto()
    Alaska = auto()
    # --snip--


@dataclass
class Nickle:
    ...


@dataclass
class Dime:
    ...


@dataclass
class Quarter:
    us_state: UsState


Coin = Nickle | Dime | Quarter


def value_in_cents(coin: Coin) -> int:
    match coin:
        case Nickle():
            return 5
        # try removing one of the `case`s
        case Dime():
            return 10
        case Quarter(state):
            print(f"State quarter from {state}")
            return 25
        case _ as u:
            assert_never(u)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant