diff --git a/mypy/typeops.py b/mypy/typeops.py index 8c53d250b576..fb7ce5f89467 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -1195,6 +1195,11 @@ class Status(Enum): return UnionType([LiteralType(True, typ), LiteralType(False, typ)]) if typ.type.is_enum: + if any(base.fullname == "enum.Flag" for base in typ.type.mro): + # The declared members of a Flag are not an exhaustive set of values: a + # value can hold any combination of members, so expanding the enum into a + # union of member literals would be unsound. + return typ items = [LiteralType(name, typ) for name in typ.type.enum_members] if not items: return typ diff --git a/test-data/unit/check-enum.test b/test-data/unit/check-enum.test index 4e8bf0a04750..8a92a51b07c7 100644 --- a/test-data/unit/check-enum.test +++ b/test-data/unit/check-enum.test @@ -473,6 +473,39 @@ if int(): x = x | C.b [builtins fixtures/enum.pyi] +[case testFlagEnumNotExpandedIntoUnion] +# A Flag value can hold any combination of members, so the declared members are not an +# exhaustive set of values: ruling out one member must not prune the others. +from enum import Flag +class Programs(Flag): + NONE = 0 + P1 = 1 + P2 = 2 + P3 = 4 +def f(programs: Programs) -> None: + if programs is Programs.NONE: + return + if programs is Programs.P2: + return + reveal_type(programs) # N: Revealed type is "__main__.Programs" + if Programs.P2 in programs: + pass +[builtins fixtures/enum.pyi] + +[case testFlagEnumExplicitLiteralUnionStillNarrows] +# Narrowing a union that was written out explicitly still removes members. +from enum import Flag +from typing import Literal +class P(Flag): + A = 1 + B = 2 +def f(p: Literal[P.A] | Literal[P.B]) -> None: + if p is P.A: + reveal_type(p) # N: Revealed type is "Literal[__main__.P.A]" + else: + reveal_type(p) # N: Revealed type is "Literal[__main__.P.B]" +[builtins fixtures/enum.pyi] + [case testEnumIntFlag] from enum import IntFlag class C(IntFlag): diff --git a/test-data/unit/lib-stub/enum.pyi b/test-data/unit/lib-stub/enum.pyi index 5047f7083804..5f0c2e979e17 100644 --- a/test-data/unit/lib-stub/enum.pyi +++ b/test-data/unit/lib-stub/enum.pyi @@ -40,6 +40,7 @@ class Flag(Enum): value: int _value_: int def __or__(self: _T, other: Union[int, _T]) -> _T: pass + def __contains__(self: _T, other: _T) -> bool: pass class IntFlag(int, Flag):