From ebeb5269a484747e8db3d7829dfcf1718334dd5c Mon Sep 17 00:00:00 2001 From: DrSkyle <86089508+DrSkyle@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:37:55 +0000 Subject: [PATCH 1/2] fix(constraints): disambiguate overloaded callables using ParamSpec hints --- mypy/constraints.py | 258 +++++++++++------- mypy/typestate.py | 4 + .../unit/check-parameter-specification.test | 29 ++ 3 files changed, 188 insertions(+), 103 deletions(-) diff --git a/mypy/constraints.py b/mypy/constraints.py index aa095316c234e..0a5ff25d43a3d 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -9,7 +9,7 @@ import mypy.typeops from mypy.argmap import ArgTypeExpander from mypy.erasetype import erase_typevars -from mypy.expandtype import expand_type_by_instance +from mypy.expandtype import expand_type, expand_type_by_instance from mypy.maptype import map_instance_to_supertype from mypy.nodes import ( ARG_OPT, @@ -136,121 +136,165 @@ def infer_constraints_for_callable( incomplete_star_mapping = True # type: ignore[unreachable] break - for i, actuals in enumerate(formal_to_actual): - if isinstance(callee.arg_types[i], UnpackType): - unpack_type = callee.arg_types[i] - assert isinstance(unpack_type, UnpackType) - - # In this case we are binding all the actuals to *args, - # and we want a constraint that the typevar tuple being unpacked - # is equal to a type list of all the actuals. - actual_types = [] - - unpacked_type = get_proper_type(unpack_type.type) - if isinstance(unpacked_type, TypeVarTupleType): - tuple_instance = unpacked_type.tuple_fallback - elif isinstance(unpacked_type, TupleType): - tuple_instance = unpacked_type.partial_fallback - else: - assert False, "mypy bug: unhandled constraint inference case" - - for actual in actuals: - actual_arg_type = arg_types[actual] - if actual_arg_type is None: - continue + pushed_hint = False + if param_spec is not None and not incomplete_star_mapping: + hint_types: list[Type] = [] + hint_names: list[str | None] = [] + hint_kinds: list[ArgKind] = [] + hint_complete = True + for i, actuals in enumerate(formal_to_actual): + if callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2): + for actual in actuals: + actual_arg_type = arg_types[actual] + if actual_arg_type is None: + hint_complete = False + break + hint_types.append( + mapper.expand_actual_type( + actual_arg_type, arg_kinds[actual], None, arg_kinds[actual] + ) + ) + actual_kind = arg_kinds[actual] + hint_kinds.append( + ARG_POS if actual_kind not in (ARG_STAR, ARG_STAR2) else actual_kind + ) + hint_names.append(arg_names[actual] if arg_names else None) + if not hint_complete: + break + if hint_complete: + type_state.param_spec_hints.append( + { + param_spec.id: Parameters( + arg_types=hint_types, + arg_kinds=hint_kinds, + arg_names=hint_names, + imprecise_arg_kinds=True, + ) + } + ) + pushed_hint = True + + try: + for i, actuals in enumerate(formal_to_actual): + if isinstance(callee.arg_types[i], UnpackType): + unpack_type = callee.arg_types[i] + assert isinstance(unpack_type, UnpackType) + + # In this case we are binding all the actuals to *args, + # and we want a constraint that the typevar tuple being unpacked + # is equal to a type list of all the actuals. + actual_types = [] + + unpacked_type = get_proper_type(unpack_type.type) + if isinstance(unpacked_type, TypeVarTupleType): + tuple_instance = unpacked_type.tuple_fallback + elif isinstance(unpacked_type, TupleType): + tuple_instance = unpacked_type.partial_fallback + else: + assert False, "mypy bug: unhandled constraint inference case" - expanded_actual = mapper.expand_actual_type( - actual_arg_type, - arg_kinds[actual], - callee.arg_names[i], - callee.arg_kinds[i], - allow_unpack=True, - ) + for actual in actuals: + actual_arg_type = arg_types[actual] + if actual_arg_type is None: + continue - if arg_kinds[actual] != ARG_STAR or isinstance( - get_proper_type(actual_arg_type), TupleType - ): - actual_types.append(expanded_actual) - else: - # If we are expanding an iterable inside * actual, append a homogeneous item instead - actual_types.append( - UnpackType(tuple_instance.copy_modified(args=[expanded_actual])) + expanded_actual = mapper.expand_actual_type( + actual_arg_type, + arg_kinds[actual], + callee.arg_names[i], + callee.arg_kinds[i], + allow_unpack=True, ) - if isinstance(unpacked_type, TypeVarTupleType): - constraints.append( - Constraint( - unpacked_type, - SUPERTYPE_OF, - TupleType(actual_types, unpacked_type.tuple_fallback), - ) - ) - elif isinstance(unpacked_type, TupleType): - # Prefixes get converted to positional args, so technically the only case we - # should have here is like Tuple[Unpack[Ts], Y1, Y2, Y3]. If this turns out - # not to hold we can always handle the prefixes too. - inner_unpack = unpacked_type.items[0] - assert isinstance(inner_unpack, UnpackType) - inner_unpacked_type = get_proper_type(inner_unpack.type) - suffix_len = len(unpacked_type.items) - 1 - if isinstance(inner_unpacked_type, TypeVarTupleType): - # Variadic item can be either *Ts... + if arg_kinds[actual] != ARG_STAR or isinstance( + get_proper_type(actual_arg_type), TupleType + ): + actual_types.append(expanded_actual) + else: + # If we are expanding an iterable inside * actual, append a homogeneous item instead + actual_types.append( + UnpackType(tuple_instance.copy_modified(args=[expanded_actual])) + ) + + if isinstance(unpacked_type, TypeVarTupleType): constraints.append( Constraint( - inner_unpacked_type, + unpacked_type, SUPERTYPE_OF, - TupleType( - actual_types[:-suffix_len], inner_unpacked_type.tuple_fallback - ), + TupleType(actual_types, unpacked_type.tuple_fallback), ) ) - else: - # ...or it can be a homogeneous tuple. - assert ( - isinstance(inner_unpacked_type, Instance) - and inner_unpacked_type.type.fullname == "builtins.tuple" - ) - for at in actual_types[:-suffix_len]: - constraints.extend( - infer_constraints(inner_unpacked_type.args[0], at, SUPERTYPE_OF) + elif isinstance(unpacked_type, TupleType): + # Prefixes get converted to positional args, so technically the only case we + # should have here is like Tuple[Unpack[Ts], Y1, Y2, Y3]. If this turns out + # not to hold we can always handle the prefixes too. + inner_unpack = unpacked_type.items[0] + assert isinstance(inner_unpack, UnpackType) + inner_unpacked_type = get_proper_type(inner_unpack.type) + suffix_len = len(unpacked_type.items) - 1 + if isinstance(inner_unpacked_type, TypeVarTupleType): + # Variadic item can be either *Ts... + constraints.append( + Constraint( + inner_unpacked_type, + SUPERTYPE_OF, + TupleType( + actual_types[:-suffix_len], inner_unpacked_type.tuple_fallback + ), + ) + ) + else: + # ...or it can be a homogeneous tuple. + assert ( + isinstance(inner_unpacked_type, Instance) + and inner_unpacked_type.type.fullname == "builtins.tuple" ) - # Now handle the suffix (if any). - if suffix_len: - for tt, at in zip(unpacked_type.items[1:], actual_types[-suffix_len:]): - constraints.extend(infer_constraints(tt, at, SUPERTYPE_OF)) + for at in actual_types[:-suffix_len]: + constraints.extend( + infer_constraints(inner_unpacked_type.args[0], at, SUPERTYPE_OF) + ) + # Now handle the suffix (if any). + if suffix_len: + for tt, at in zip(unpacked_type.items[1:], actual_types[-suffix_len:]): + constraints.extend(infer_constraints(tt, at, SUPERTYPE_OF)) + else: + assert False, "mypy bug: unhandled constraint inference case" else: - assert False, "mypy bug: unhandled constraint inference case" - else: - for actual in actuals: - actual_arg_type = arg_types[actual] - if actual_arg_type is None: - continue + for actual in actuals: + actual_arg_type = arg_types[actual] + if actual_arg_type is None: + continue - if param_spec and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2): - # If actual arguments are mapped to ParamSpec type, we can't infer individual - # constraints, instead store them and infer single constraint at the end. - # It is impossible to map actual kind to formal kind, so use some heuristic. - # This inference is used as a fallback, so relying on heuristic should be OK. - if not incomplete_star_mapping: - param_spec_arg_types.append( - mapper.expand_actual_type( - actual_arg_type, arg_kinds[actual], None, arg_kinds[actual] + if param_spec and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2): + # If actual arguments are mapped to ParamSpec type, we can't infer individual + # constraints, instead store them and infer single constraint at the end. + # It is impossible to map actual kind to formal kind, so use some heuristic. + # This inference is used as a fallback, so relying on heuristic should be OK. + if not incomplete_star_mapping: + param_spec_arg_types.append( + mapper.expand_actual_type( + actual_arg_type, arg_kinds[actual], None, arg_kinds[actual] + ) ) + actual_kind = arg_kinds[actual] + param_spec_arg_kinds.append( + ARG_POS + if actual_kind not in (ARG_STAR, ARG_STAR2) + else actual_kind + ) + param_spec_arg_names.append(arg_names[actual] if arg_names else None) + else: + actual_type = mapper.expand_actual_type( + actual_arg_type, + arg_kinds[actual], + callee.arg_names[i], + callee.arg_kinds[i], ) - actual_kind = arg_kinds[actual] - param_spec_arg_kinds.append( - ARG_POS if actual_kind not in (ARG_STAR, ARG_STAR2) else actual_kind - ) - param_spec_arg_names.append(arg_names[actual] if arg_names else None) - else: - actual_type = mapper.expand_actual_type( - actual_arg_type, - arg_kinds[actual], - callee.arg_names[i], - callee.arg_kinds[i], - ) - c = infer_constraints(callee.arg_types[i], actual_type, SUPERTYPE_OF) - constraints.extend(c) + c = infer_constraints(callee.arg_types[i], actual_type, SUPERTYPE_OF) + constraints.extend(c) + finally: + if pushed_hint: + type_state.param_spec_hints.pop() if ( param_spec and not any(c.type_var == param_spec.id for c in constraints) @@ -1291,7 +1335,15 @@ def infer_against_overloaded( # the first overload item that is callable compatible. This # seems to work somewhat well, but we should really use a more # reliable technique. - item = find_matching_overload_item(overloaded, template) + match_template = template + template_ps = template.param_spec() + if template_ps is not None and type_state.param_spec_hints: + hint = type_state.param_spec_hints[-1].get(template_ps.id) + if hint is not None: + expanded = expand_type(template, {template_ps.id: hint}) + if isinstance(expanded, CallableType): + match_template = expanded + item = find_matching_overload_item(overloaded, match_template) if ret_only: return infer_constraints(template.ret_type, item.ret_type, self.direction) return infer_constraints(template, item, self.direction) diff --git a/mypy/typestate.py b/mypy/typestate.py index aa4893ca45038..87fdffdb76af1 100644 --- a/mypy/typestate.py +++ b/mypy/typestate.py @@ -13,6 +13,7 @@ from mypy.types import ( CallableType, Instance, + Parameters, Type, TypeVarId, TypeVarLikeType, @@ -108,6 +109,8 @@ class TypeState: _assuming_proper: Final[list[tuple[Type, Type]]] # Ditto for inference of generic constraints against recursive type aliases. inferring: Final[list[tuple[Type, Type]]] + # Stack of ParamSpec argument hints from call sites to disambiguate overloaded callables. + param_spec_hints: Final[list[dict[TypeVarId, Parameters]]] # Whether to use joins or unions when solving constraints, see checkexpr.py for details. infer_unions: bool # Whether to use new type inference algorithm that can infer polymorphic types. @@ -138,6 +141,7 @@ def __init__(self) -> None: self._assuming = [] self._assuming_proper = [] self.inferring = [] + self.param_spec_hints = [] self.infer_unions = False self.infer_polymorphic = False self.keep_unions = False diff --git a/test-data/unit/check-parameter-specification.test b/test-data/unit/check-parameter-specification.test index 18e16179854fb..aeab59d4c483f 100644 --- a/test-data/unit/check-parameter-specification.test +++ b/test-data/unit/check-parameter-specification.test @@ -2848,3 +2848,32 @@ def test(x: C[I]) -> list[int]: ... ci: C[int] f: list[int] = apply(test, ci) [builtins fixtures/paramspec.pyi] + +[case testParamSpecTwoSidedOverloadDisambiguation] +from typing import Callable, Protocol, TypeVar, overload +from typing_extensions import ParamSpec + +P = ParamSpec("P") +R = TypeVar("R") +T = TypeVar("T") + +class OverloadedProto(Protocol): + @overload + def __call__(self, x: int, y: int) -> int: ... + @overload + def __call__(self, x: str, *, flag: bool = False) -> str: ... + +@overload +def ov(x: int, y: int) -> int: ... +@overload +def ov(x: str, *, flag: bool = False) -> str: ... +def ov(*args: object, **kwargs: object) -> object: ... + +def run(fn: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> list[R]: ... +def unwrap(x: list[T]) -> T: ... + +def f(p: OverloadedProto) -> None: + reveal_type(unwrap(run(p, "hello", flag=True))) # N: Revealed type is "builtins.str" + reveal_type(unwrap(run(ov, "hello", flag=True))) # N: Revealed type is "builtins.str" +[builtins fixtures/paramspec.pyi] + From d6bc93cf2c1d652bbf017716fd2090cd66622557 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:00:08 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- test-data/unit/check-parameter-specification.test | 1 - 1 file changed, 1 deletion(-) diff --git a/test-data/unit/check-parameter-specification.test b/test-data/unit/check-parameter-specification.test index aeab59d4c483f..a27a0191b809d 100644 --- a/test-data/unit/check-parameter-specification.test +++ b/test-data/unit/check-parameter-specification.test @@ -2876,4 +2876,3 @@ def f(p: OverloadedProto) -> None: reveal_type(unwrap(run(p, "hello", flag=True))) # N: Revealed type is "builtins.str" reveal_type(unwrap(run(ov, "hello", flag=True))) # N: Revealed type is "builtins.str" [builtins fixtures/paramspec.pyi] -