diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index c48f3da51f85..7008c7e41586 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -2292,8 +2292,28 @@ def infer_function_type_arguments_both_sides( arg_types = self.infer_arg_types_in_context( pass2_callee_type, args, arg_kinds, formal_to_actual ) + # Preserve inferred ParamSpecs when selecting overloads in the second pass. + # Using the original Callable[P, T] could select an incompatible overload, + # but ordinary type variables must remain free to infer narrower types. + infer_callee_type = initial_callee_type + if any(isinstance(v, ParamSpecType) for v in type_vars): + infer_callee_type = self.apply_generic_arguments( + initial_callee_type, + [ + a if isinstance(v, ParamSpecType) else None + for v, a in zip(type_vars, solid_inferred_args) + ], + context, + ) + initial_formal_to_actual = map_actuals_to_formals( + arg_kinds, + arg_names, + infer_callee_type.arg_kinds, + infer_callee_type.arg_names, + lambda a: self.accept(args[a]), + ) inferred_args, _ = infer_function_type_arguments( - initial_callee_type, + infer_callee_type, arg_types, arg_kinds, arg_names, @@ -2301,6 +2321,10 @@ def infer_function_type_arguments_both_sides( context=self.argument_infer_context(), extra_constraints=constraints, ) + inferred_by_id = dict(zip((v.id for v in infer_callee_type.variables), inferred_args)) + inferred_args = [ + inferred_by_id.get(v.id, a) for v, a in zip(type_vars, solid_inferred_args) + ] # Only use two-side inference if it is fully successful, # otherwise, fallback to return type context as a tiebreaker. diff --git a/test-data/unit/check-parameter-specification.test b/test-data/unit/check-parameter-specification.test index 18e16179854f..90ba82f86636 100644 --- a/test-data/unit/check-parameter-specification.test +++ b/test-data/unit/check-parameter-specification.test @@ -2848,3 +2848,26 @@ def test(x: C[I]) -> list[int]: ... ci: C[int] f: list[int] = apply(test, ci) [builtins fixtures/paramspec.pyi] + +[case testTwoSidedInferenceWithParamSpecOverload] +from typing import Callable, TypeVar, overload +from typing_extensions import ParamSpec + +P = ParamSpec("P") +T = TypeVar("T") + +def apply(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> list[T]: ... +def consume(value: list[T]) -> T: ... + +@overload +def func(value: int, required: str) -> int: ... +@overload +def func(value: int, *, optional: int = 0) -> int: ... +def func(value: int, required: str = "", *, optional: int = 0) -> int: ... + +reveal_type(consume(apply(func, 1))) # N: Revealed type is "builtins.int" +reveal_type(consume(apply(func, 1, optional=0))) # N: Revealed type is "builtins.int" +reveal_type(consume(apply(func, 1, ""))) # N: Revealed type is "builtins.int" +result = apply(func, 1) +reveal_type(consume(result)) # N: Revealed type is "builtins.int" +[builtins fixtures/paramspec.pyi]