From 621521488201307d1923778ab31c545e2841301b Mon Sep 17 00:00:00 2001 From: mengqing <2285465807@qq.com> Date: Wed, 11 Nov 2026 23:20:20 +0800 Subject: [PATCH] Bind type variables in ParamSpec callable aliases --- mypy/typeanal.py | 128 ++++++++++++++++++ .../unit/check-parameter-specification.test | 28 ++++ test-data/unit/check-python312.test | 11 ++ 3 files changed, 167 insertions(+) diff --git a/mypy/typeanal.py b/mypy/typeanal.py index bd6f97cc94cef..e5063ba229857 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -484,6 +484,21 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) return special if isinstance(node, TypeAlias): self.aliases_used.add(fullname) + if ( + isinstance(get_proper_type(node.target), CallableType) + and not self.defining_alias + and not self.analyzing_tvar_def + and HasUnboundTypeVar(self.api, self.tvar_scope).query_types(t.args) + ): + # A type variable in the arguments of a callable-valued + # alias may belong to the callable itself, as in a literal + # Callable[..., T], rather than to the enclosing scope. + # Expand the alias and analyze the resulting callable, so + # that it binds the type variable. See + # https://github.com/python/mypy/issues/22399. + expanded = self.expand_alias_for_callable(node, t) + if expanded is not None: + return expanded an_args = self.anal_array( t.args, allow_param_spec=True, @@ -546,6 +561,60 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) else: # sym is None return AnyType(TypeOfAny.special_form) + def expand_alias_for_callable(self, node: TypeAlias, t: UnboundType) -> Type | None: + """Expand a callable-valued alias, binding free type variables to the callable. + + When a generic alias over a Callable is applied to arguments containing + a type variable that is not bound in the enclosing scope (e.g. + ``Alias[[int], T]`` where ``Alias = Callable[P, T]``), the type + variable belongs to the callable itself, as in a literal + ``Callable[[int], T]``. Analyze the arguments allowing unbound type + variables, expand the alias, and analyze the resulting callable, so + that it binds the type variable. See + https://github.com/python/mypy/issues/22399. + + Return the analyzed callable type, or None if the alias could not be + expanded to a callable (in which case the caller falls back to the + regular analysis). + """ + old_allow_unbound_tvars = self.allow_unbound_tvars + self.allow_unbound_tvars = True + try: + an_args = self.anal_array( + t.args, + allow_param_spec=True, + allow_param_spec_literals=node.has_param_spec_type, + allow_unpack=True, + ) + finally: + self.allow_unbound_tvars = old_allow_unbound_tvars + if node.has_param_spec_type and len(node.alias_tvars) == 1: + an_args = self.pack_paramspec_args(an_args, t.empty_tuple_index) + res, _ = instantiate_type_alias( + node, + an_args, + self.fail, + self.note, + node.no_args, + t, + self.options, + unexpanded_type=t, + disallow_any=self.options.disallow_any_generics and not self.is_typeshed_stub, + empty_tuple_index=t.empty_tuple_index, + analyzing_tvar_def=self.analyzing_tvar_def, + ) + if not isinstance(res, TypeAliasType): + return None + expanded = get_proper_type(res) + if not isinstance(expanded, CallableType): + return None + analyzed = get_proper_type(expanded.accept(self)) + assert isinstance(analyzed, CallableType) + # Analyzing the callable binds its free type variables, but it does + # not resolve occurrences nested inside instances or alias + # applications. Replace those with the callable's own type variables. + return analyzed.accept(ResolveUnboundTypeVars(analyzed.variables)) + def pack_paramspec_args(self, an_args: Sequence[Type], empty_tuple_index: bool) -> list[Type]: # "Aesthetic" ParamSpec literals for single ParamSpec: C[int, str] -> C[[int, str]]. # These do not support mypy_extensions VarArgs, etc. as they were already analyzed @@ -2756,6 +2825,65 @@ def unknown_unpack(t: Type) -> bool: return False +class HasUnboundTypeVar(TypeQuery[bool]): + """Whether a type contains a reference to an unbound type variable. + + An unbound type variable is represented by an UnboundType node referring + to a type variable (or ParamSpec, or TypeVarTuple) that is not bound in + the current scope. + + References nested inside another callable type are not reported: a + callable binds its own type variables when it is analyzed. References + nested inside another alias application are reported: an alias + application is analyzed in the enclosing scope, so such a type variable + does not belong to the nested alias. + """ + + def __init__(self, api: SemanticAnalyzerCoreInterface, scope: TypeVarLikeScope) -> None: + super().__init__() + self.api = api + self.scope = scope + + def strategy(self, items: list[bool]) -> bool: + return any(items) + + def visit_unbound_type(self, t: UnboundType) -> bool: + sym = self.api.lookup_qualified(t.name, t, suppress_errors=True) + if sym is not None: + if isinstance(sym.node, TypeVarLikeExpr) and self.scope.get_binding(sym) is None: + return True + return self.query_types(t.args) + + def visit_callable_type(self, t: CallableType) -> bool: + return False + + def visit_type_alias_type(self, t: TypeAliasType) -> bool: + return self.query_types(t.args) + + +class ResolveUnboundTypeVars(TrivialSyntheticTypeTranslator): + """Replace unbound type variables with the type variables of a callable. + + When a callable is expanded from a generic alias, analyzing it binds + its free type variables, but it does not resolve occurrences nested + inside instances or alias applications. Replace such occurrences with + the callable's own type variables of the same name. + """ + + def __init__(self, variables: Sequence[TypeVarLikeType]) -> None: + super().__init__() + self.variables = {var.name: var for var in variables} + + def visit_unbound_type(self, t: UnboundType) -> Type: + var = self.variables.get(t.name) + if var is not None and not t.args: + return var.copy_modified(id=var.id, line=t.line, column=t.column) + return t.copy_modified(args=[arg.accept(self) for arg in t.args]) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t.copy_modified(args=[arg.accept(self) for arg in t.args]) + + class FindTypeVarVisitor(SyntheticTypeVisitor[None]): """Type visitor that looks for type variable types and self types.""" diff --git a/test-data/unit/check-parameter-specification.test b/test-data/unit/check-parameter-specification.test index 18e16179854fb..4ab34b53a8744 100644 --- a/test-data/unit/check-parameter-specification.test +++ b/test-data/unit/check-parameter-specification.test @@ -2847,4 +2847,32 @@ def apply(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: ... def test(x: C[I]) -> list[int]: ... ci: C[int] f: list[int] = apply(test, ci) +[builtins fixtures/tuple.pyi] + +[case testParamSpecAliasUnboundTypeVar] +from typing import Callable, Generic, ParamSpec, TypeVar +from typing_extensions import TypeAlias + +P = ParamSpec("P") +T = TypeVar("T") +T2 = TypeVar("T2") + +Alias: TypeAlias = Callable[P, T] +NoParamSpec: TypeAlias = Callable[[int], T] + +def plain() -> Callable[[int], T]: ... +def no_paramspec_alias() -> NoParamSpec[T]: ... +def paramspec_alias() -> Alias[[int], T]: ... +def paramspec_alias_ellipsis() -> Alias[..., T]: ... + +reveal_type(plain) # N: Revealed type is "def () -> def [T] (builtins.int) -> T`-1" +reveal_type(no_paramspec_alias) # N: Revealed type is "def [T] () -> def (builtins.int) -> T`-1" +reveal_type(paramspec_alias) # N: Revealed type is "def () -> def [T] (builtins.int) -> T`-1" +reveal_type(paramspec_alias_ellipsis) # N: Revealed type is "def () -> def [T] (*Any, **Any) -> T`-1" + +class Chain(Generic[P, T]): ... +Dec: TypeAlias = Callable[[Chain[P, T]], Chain[P, T2]] + +def identity() -> Dec[..., T, T]: ... +reveal_type(identity) # N: Revealed type is "def () -> def [T] (__main__.Chain[[*Any, **Any], T`-1]) -> __main__.Chain[[*Any, **Any], T`-1]" [builtins fixtures/paramspec.pyi] diff --git a/test-data/unit/check-python312.test b/test-data/unit/check-python312.test index b756da6ea9b30..280ff3256ee1f 100644 --- a/test-data/unit/check-python312.test +++ b/test-data/unit/check-python312.test @@ -2469,3 +2469,14 @@ reveal_type(a[0]) # N: Revealed type is "tuple[builtins.int, builtins.str]" reveal_type(a[1]) # N: Revealed type is "tuple[builtins.int, builtins.str]" reveal_type(a[2]) # N: Revealed type is "builtins.tuple[Any, ...]" [builtins fixtures/tuple.pyi] + +[case testPEP695ParamSpecAliasUnboundTypeVar] +from typing import Callable + +type Alias[**P, T] = Callable[P, T] + +def paramspec_alias[T]() -> Alias[[int], T]: ... + +reveal_type(paramspec_alias) # N: Revealed type is "def () -> def [T] (builtins.int) -> T`-1" +[builtins fixtures/tuple.pyi] +[typing fixtures/typing-full.pyi]