diff --git a/mypy/solve.py b/mypy/solve.py index 4a5eec47ca60..df059d61e8c3 100644 --- a/mypy/solve.py +++ b/mypy/solve.py @@ -7,6 +7,7 @@ from typing import TypeAlias as _TypeAlias from mypy.constraints import SUBTYPE_OF, SUPERTYPE_OF, Constraint, infer_constraints, neg_op +from mypy.erasetype import remove_instance_last_known_values from mypy.expandtype import expand_type from mypy.graph_utils import prepare_sccs, strongly_connected_components, topsort from mypy.join import join_type_list @@ -322,7 +323,9 @@ def solve_one(lowers: Iterable[Type], uppers: Iterable[Type]) -> Type | None: return None elif top is None: candidate = bottom - elif is_subtype(bottom, top): + # Last known values are erased after inference, so they must not be needed + # for the inferred type to satisfy the upper bound. + elif is_subtype(remove_instance_last_known_values(bottom), top): candidate = bottom else: candidate = None diff --git a/test-data/unit/check-literal.test b/test-data/unit/check-literal.test index b54db1f33fa5..011f241e57e6 100644 --- a/test-data/unit/check-literal.test +++ b/test-data/unit/check-literal.test @@ -1190,6 +1190,31 @@ reveal_type(d) # N: Revealed type is "tuple[builtins.int, builtins.int]" [builtins fixtures/tuple.pyi] [out] +[case testLiteralEnumTupleUnionInSequenceContext] +from enum import Enum +from typing import Literal, Sequence + +class Color(Enum): + RED = 1 + BLUE = 2 + +class Shape(Enum): + CIRCLE = 1 + TRIANGLE = 2 + SQUARE = 3 + +Pair = tuple[Literal[Color.RED], Literal[Shape.CIRCLE]] | tuple[Literal[Color.BLUE], Literal[Shape.TRIANGLE]] + +def consume(pairs: Sequence[Pair]) -> None: pass + +consume([(Color.BLUE, Shape.TRIANGLE)]) +consume([(Color.RED, Shape.CIRCLE)]) +consume([(Color.BLUE, Shape.TRIANGLE), (Color.RED, Shape.CIRCLE)]) +consume([(Color.RED, Shape.CIRCLE), (Color.BLUE, Shape.TRIANGLE)]) +consume([(Color.BLUE, Shape.CIRCLE)]) # E: List item 0 has incompatible type "tuple[Color, Shape]"; expected "tuple[Literal[Color.RED], Literal[Shape.CIRCLE]] | tuple[Literal[Color.BLUE], Literal[Shape.TRIANGLE]]" +consume([(Color.BLUE, Shape.SQUARE)]) # E: List item 0 has incompatible type "tuple[Color, Shape]"; expected "tuple[Literal[Color.RED], Literal[Shape.CIRCLE]] | tuple[Literal[Color.BLUE], Literal[Shape.TRIANGLE]]" +[builtins fixtures/tuple.pyi] + [case testLiteralInferredInDictContext] from typing import Dict, Literal