diff --git a/mypy/solve.py b/mypy/solve.py index 4a5eec47ca60..b6c324c7a304 100644 --- a/mypy/solve.py +++ b/mypy/solve.py @@ -323,6 +323,17 @@ def solve_one(lowers: Iterable[Type], uppers: Iterable[Type]) -> Type | None: elif top is None: candidate = bottom elif is_subtype(bottom, top): + # An invariant context can set the same union as both a lower and an + # upper bound. Keep it if it already accepts every lower bound: the join + # can add redundant members when compatibility depends on Any. + if ( + isinstance(p_top, UnionType) + and isinstance(p_bottom, UnionType) + and p_top != p_bottom + and top in lowers + and all(is_subtype(lower, top) for lower in lowers) + ): + return top candidate = bottom else: candidate = None diff --git a/test-data/unit/check-inference-context.test b/test-data/unit/check-inference-context.test index ece2dc32a9b5..e44c9fe4e16e 100644 --- a/test-data/unit/check-inference-context.test +++ b/test-data/unit/check-inference-context.test @@ -1691,3 +1691,19 @@ def run(x: list[T], fn: Callable[[T], S]) -> list[Optional[S]]: ... def worker(d: int) -> Optional[int]: ... res: list[Optional[int]] = run([1, 2, 3], worker) # OK + +[case testInferenceContextOptionalDictOfCallableUnion] +from typing import Any, Callable, TypeVar + +T = TypeVar("T") +CallableOne = Callable[[T], None] +CallableTwo = Callable[[T, bool], None] +CallableUnion = CallableOne[T] | CallableTwo[T] +CallableUnionDict = dict[str, CallableUnion[T]] | None + +def f(data: int, flag: bool) -> None: + pass + +test_dict: dict[type, CallableUnionDict[Any]] = {int: {"test": f}} +[builtins fixtures/dict.pyi] +[out]