From d5d51ae9c6ecfbaa2ddc45be272c6d01e2eb2073 Mon Sep 17 00:00:00 2001 From: zhengdaodeguL <1159957339@qq.com> Date: Thu, 19 Nov 2026 06:21:30 +0000 Subject: [PATCH] Fix spurious error on optional dict of generic callable union Fixes #22513 In solve_one, an invariant context could set the same union as both a lower and an upper bound. The join of the lower bounds could then add redundant members when compatibility depended on Any, widening the inferred value type and leaving the outer dict with two competing dict alternatives. Keep the original union when it already accepts every lower bound. --- mypy/solve.py | 11 +++++++++++ test-data/unit/check-inference-context.test | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/mypy/solve.py b/mypy/solve.py index 4a5eec47ca60d..b6c324c7a3047 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 ece2dc32a9b54..e44c9fe4e16e6 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]