Skip to content

Enum exhaustiveness checking only works using "is" comparisons, not "==", conflicting with docs #14823

Description

@jonasrauber

The docs contain this example (simplified):

fromenumimportEnumfromtyping_extensionsimportassert_neverclassDirection(Enum):
up='up'down='down'defchoose_direction(direction: Direction) ->None:
ifdirectionisDirection.up:
print('Going up!')
returnelifdirectionisDirection.down:
print('Down')
returnassert_never(direction)

This works. But if we switch to "==" for comparisons, it fails:

fromenumimportEnumfromtyping_extensionsimportassert_neverclassDirection(Enum):
up='up'down='down'defchoose_direction(direction: Direction) ->None:
ifdirection==Direction.up:
print('Going up!')
returnelifdirection==Direction.down:
print('Down')
returnassert_never(direction)

error: Argument 1 to "assert_never" has incompatible type "Direction"; expected "NoReturn"

This is problematic, because the docs also have another example that uses == for comparison and implies that it would work if the second clause would be added.

defchoose_direction(direction: Direction) ->None:
ifdirection==Direction.up:
print('Going up!')
returnassert_never(direction) # E: Argument 1 to "assert_never" has incompatible type "Direction"; expected "NoReturn"

Beyond the docs, this is problematic, because we can have enums that subclass the value type, e.g.

classDirection(str, Enum):
up='up'down='down'

Now it actually makes a difference at runtime whether we compare with is or ==, because == also matches normal strings 'up' and 'down', is does not.

Your Environment

Reproduced in Python 3.9 w/ typing_extensions and Python 3.11, using Mypy 1.0.1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions