Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 33 additions & 0 deletions test-data/unit/check-enum.test
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
1 change: 1 addition & 0 deletions test-data/unit/lib-stub/enum.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading