Skip to content

Commit

Permalink
Use upper bounds as fallback solutions for inference (#16184)
Browse files Browse the repository at this point in the history
Fixes #13220

This looks a bit ad-hoc, but it is probably the least disruptive
solution possible.
  • Loading branch information
ilevkivskyi committed Sep 27, 2023
1 parent 4b66fa9 commit 5f6961b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
35 changes: 35 additions & 0 deletions mypy/solve.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,13 @@ def solve_constraints(
else:
candidate = AnyType(TypeOfAny.special_form)
res.append(candidate)

if not free_vars:
# Most of the validation for solutions is done in applytype.py, but here we can
# quickly test solutions w.r.t. to upper bounds, and use the latter (if possible),
# if solutions are actually not valid (due to poor inference context).
res = pre_validate_solutions(res, original_vars, constraints)

return res, free_vars


Expand Down Expand Up @@ -487,3 +494,31 @@ def check_linear(scc: set[TypeVarId], lowers: Bounds, uppers: Bounds) -> bool:
def get_vars(target: Type, vars: list[TypeVarId]) -> set[TypeVarId]:
"""Find type variables for which we are solving in a target type."""
return {tv.id for tv in get_all_type_vars(target)} & set(vars)


def pre_validate_solutions(
solutions: list[Type | None],
original_vars: Sequence[TypeVarLikeType],
constraints: list[Constraint],
) -> list[Type | None]:
"""Check is each solution satisfies the upper bound of the corresponding type variable.
If it doesn't satisfy the bound, check if bound itself satisfies all constraints, and
if yes, use it instead as a fallback solution.
"""
new_solutions: list[Type | None] = []
for t, s in zip(original_vars, solutions):
if s is not None and not is_subtype(s, t.upper_bound):
bound_satisfies_all = True
for c in constraints:
if c.op == SUBTYPE_OF and not is_subtype(t.upper_bound, c.target):
bound_satisfies_all = False
break
if c.op == SUPERTYPE_OF and not is_subtype(c.target, t.upper_bound):
bound_satisfies_all = False
break
if bound_satisfies_all:
new_solutions.append(t.upper_bound)
continue
new_solutions.append(s)
return new_solutions
8 changes: 8 additions & 0 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -3542,6 +3542,14 @@ T = TypeVar("T")
def type_or_callable(value: T, tp: Union[Type[T], Callable[[int], T]]) -> T: ...
reveal_type(type_or_callable(A("test"), A)) # N: Revealed type is "__main__.A"

[case testUpperBoundAsInferenceFallback]
from typing import Callable, TypeVar, Any, Mapping, Optional
T = TypeVar("T", bound=Mapping[str, Any])
def raises(opts: Optional[T]) -> T: pass
def assertRaises(cb: Callable[..., object]) -> None: pass
assertRaises(raises) # OK
[builtins fixtures/dict.pyi]

[case testJoinWithAnyFallback]
from unknown import X # type: ignore[import]

Expand Down

0 comments on commit 5f6961b

Please sign in to comment.