Skip to content
Closed
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
11 changes: 11 additions & 0 deletions mypy/solve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-inference-context.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Loading