Skip to content

Support exhaustiveness checking for 'in' statements (enums) #16093

Open
Malika1109/mypy
#3
@chrisbeardy

Description

@chrisbeardy

Feature

Allow the use of the in statement when doing exhaustiveness checking.

from enum import Enum
from typing import assert_never


class MyEnum(Enum):
    A = 1
    B = 2
    C = 3 


def my_function(a: MyEnum) -> bool:
    if a == MyEnum.A:
        return True
    elif a in (MyEnum.B, MyEnum.C):
        return False
    assert_never(a)


my_function(MyEnum.A)

Currently, this will raise the following exception:

error: Argument 1 to "assert_never" has incompatible type
"Literal[MyEnum.B, MyEnum.C]"; expected "NoReturn"  [arg-type]
        assert_never(a)

where the following would not:

def my_function(a: MyEnum) -> bool:
    if a == MyEnum.A:
        return True
    elif a == MyEnum.B:
        return False
    elif a == MyEnum.C:
        return False
    assert_never(a)

Pitch

If you wish to do the same thing for multiple enums in that particular function and also want exhaustiveness checking, you need to type each case out individually and then return the same thing, which is not great (DRY etc...).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions