GeezerVison is showing github.com — Support enum type narrowing with `in` · Issue #13684 · python/mypy
Support enum type narrowing with in #13684
Description
The syntax some_enum_value in [list_of_values] should narrow the enum to that list of values.
This is a list extension to #10915 "support narrowing enum values using == and !="
Unlike the == case, there is no equivalent is syntax for lists that will narrow the type.
This example shows the motivation for this feature, as well as the syntax that is expected to work.
from typing import Literal, Union, cast
from enum import Enum
class SomeType(Enum):
a = 1
b = 2
c = 3
LimitType = Union[Literal[SomeType.a, SomeType.b]]
AllowedLimitType = [SomeType.a, SomeType.b]
def inner_check(limit: LimitType) -> None:
pass
def outer_check(some: SomeType) -> None:
if some in [SomeType.a, SomeType.b]:
inner_check(some) # Incompatible type
if some in AllowedLimitType:
inner_check(some) # Incompatible type
if some == SomeType.a or some == SomeType.b:
inner_check(some) # Incompatible type
inner_check(cast(LimitType, some))
if some is SomeType.a or some is SomeType.b:
inner_check(some)
if some == SomeType.a:
inner_check(SomeType.a)
# This would be ideal
# if some in LimitType:
# inner_check(some)
def main() -> None:
outer_check(SomeType.a)
main()
Reacted by Marti Raudsepp, IvarVirusiim, Finite State Machine, Fabian Keller, Tomer Bin, adasium and Cal Jacobson
Activity
intgr commented on Apr 25, 2023
hauntsaninja commented on Feb 10, 2026
(Note behaviour on master is better here if you use a tuple instead of a list)
added a commit that references this issue
on May 13, 2026This issue will close once commit d2b0234 is merged into the 'master' branch.d2b0234
Metadata
Metadata
Development
No branches or pull requestsIssue actions