Skip to content

Commit db11aa5

Browse files
author
hauntsaninja
committed
Allow narrowing enum values using ==
Resolves python#10915, resolves python#9786 See the discussion in python#10915. I'm sympathetic to the difference between identity and equality here being surprising and that mypy doesn't usually make concessions to mutability when type checking. The old test cases are pretty explicit about their intentions and are worth reading. Curious to see what people (and mypy-primer) have to say about this.
1 parent 47b22c5 commit db11aa5

2 files changed

Lines changed: 42 additions & 25 deletions

File tree

‎mypy/checker.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4802,7 +4802,15 @@ def refine_identity_comparison_expression(self,
48024802
"""
48034803
should_coerce = True
48044804
if coerce_only_in_literal_context:
4805-
should_coerce = any(is_literal_type_like(operand_types[i]) for i in chain_indices)
4805+
4806+
def should_coerce_inner(typ: Type) -> bool:
4807+
typ = get_proper_type(typ)
4808+
return is_literal_type_like(typ) or (
4809+
isinstance(typ, Instance)
4810+
and typ.type.is_enum
4811+
)
4812+
4813+
should_coerce = any(should_coerce_inner(operand_types[i]) for i in chain_indices)
48064814

48074815
target: Optional[Type] = None
48084816
possible_target_indices = []

‎test-data/unit/check-narrowing.test‎

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -699,47 +699,47 @@ class FlipFlopStr:
699699
def mutate(self) -> None:
700700
self.state = "state-2" if self.state == "state-1" else "state-1"
701701

702-
def test1(switch: FlipFlopEnum) -> None:
702+
703+
def test1(switch: FlipFlopStr) -> None:
703704
# Naively, we might assume the 'assert' here would narrow the type to
704-
# Literal[State.A]. However, doing this ends up breaking a fair number of real-world
705+
# Literal["state-1"]. However, doing this ends up breaking a fair number of real-world
705706
# code (usually test cases) that looks similar to this function: e.g. checks
706707
# to make sure a field was mutated to some particular value.
707708
#
708709
# And since mypy can't really reason about state mutation, we take a conservative
709710
# approach and avoid narrowing anything here.
710711

711-
assert switch.state == State.A
712-
reveal_type(switch.state) # N: Revealed type is "__main__.State"
712+
assert switch.state == "state-1"
713+
reveal_type(switch.state) # N: Revealed type is "builtins.str"
713714

714715
switch.mutate()
715716

716-
assert switch.state == State.B
717-
reveal_type(switch.state) # N: Revealed type is "__main__.State"
717+
assert switch.state == "state-2"
718+
reveal_type(switch.state) # N: Revealed type is "builtins.str"
718719

719720
def test2(switch: FlipFlopEnum) -> None:
720-
# So strictly speaking, we ought to do the same thing with 'is' comparisons
721-
# for the same reasons as above. But in practice, not too many people seem to
722-
# know that doing 'some_enum is MyEnum.Value' is idiomatic. So in practice,
723-
# this is probably good enough for now.
721+
# This is the same thing as 'test1', except we use enums, which we allow to be narrowed
722+
# to literals.
724723

725-
assert switch.state is State.A
724+
assert switch.state == State.A
726725
reveal_type(switch.state) # N: Revealed type is "Literal[__main__.State.A]"
727726

728727
switch.mutate()
729728

730-
assert switch.state is State.B # E: Non-overlapping identity check (left operand type: "Literal[State.A]", right operand type: "Literal[State.B]")
729+
assert switch.state == State.B # E: Non-overlapping equality check (left operand type: "Literal[State.A]", right operand type: "Literal[State.B]")
731730
reveal_type(switch.state) # E: Statement is unreachable
732731

733-
def test3(switch: FlipFlopStr) -> None:
734-
# This is the same thing as 'test1', except we try using str literals.
732+
def test3(switch: FlipFlopEnum) -> None:
733+
# Same thing, but using 'is' comparisons. Previously mypy's behaviour differed
734+
# here, narrowing when using 'is', but not when using '=='.
735735

736-
assert switch.state == "state-1"
737-
reveal_type(switch.state) # N: Revealed type is "builtins.str"
736+
assert switch.state is State.A
737+
reveal_type(switch.state) # N: Revealed type is "Literal[__main__.State.A]"
738738

739739
switch.mutate()
740740

741-
assert switch.state == "state-2"
742-
reveal_type(switch.state) # N: Revealed type is "builtins.str"
741+
assert switch.state is State.B # E: Non-overlapping identity check (left operand type: "Literal[State.A]", right operand type: "Literal[State.B]")
742+
reveal_type(switch.state) # E: Statement is unreachable
743743
[builtins fixtures/primitives.pyi]
744744

745745
[case testNarrowingEqualityRequiresExplicitStrLiteral]
@@ -791,6 +791,7 @@ reveal_type(x_union) # N: Revealed type is "Union[Literal['A'], Literal['B'
791791

792792
[case testNarrowingEqualityRequiresExplicitEnumLiteral]
793793
# flags: --strict-optional
794+
from typing import Union
794795
from typing_extensions import Literal, Final
795796
from enum import Enum
796797

@@ -801,26 +802,34 @@ class Foo(Enum):
801802
A_final: Final = Foo.A
802803
A_literal: Literal[Foo.A]
803804

804-
# See comments in testNarrowingEqualityRequiresExplicitStrLiteral and
805-
# testNarrowingEqualityFlipFlop for more on why we can't narrow here.
805+
# Note this is unlike testNarrowingEqualityRequiresExplicitStrLiteral
806+
# See also testNarrowingEqualityFlipFlop
806807
x1: Foo
807808
if x1 == Foo.A:
808-
reveal_type(x1) # N: Revealed type is "__main__.Foo"
809+
reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.A]"
809810
else:
810-
reveal_type(x1) # N: Revealed type is "__main__.Foo"
811+
reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.B]"
811812

812813
x2: Foo
813814
if x2 == A_final:
814-
reveal_type(x2) # N: Revealed type is "__main__.Foo"
815+
reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.A]"
815816
else:
816-
reveal_type(x2) # N: Revealed type is "__main__.Foo"
817+
reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.B]"
817818

818819
# But we let this narrow since there's an explicit literal in the RHS.
819820
x3: Foo
820821
if x3 == A_literal:
821822
reveal_type(x3) # N: Revealed type is "Literal[__main__.Foo.A]"
822823
else:
823824
reveal_type(x3) # N: Revealed type is "Literal[__main__.Foo.B]"
825+
826+
827+
class SingletonFoo(Enum):
828+
A = "A"
829+
830+
def bar(x: Union[SingletonFoo, Foo], y: SingletonFoo) -> None:
831+
if x == y:
832+
reveal_type(x) # N: Revealed type is "Literal[__main__.SingletonFoo.A]"
824833
[builtins fixtures/primitives.pyi]
825834

826835
[case testNarrowingEqualityDisabledForCustomEquality]

0 commit comments

Comments
 (0)