From 0df84e14c38dd97a5dd7d51a6c9317932fc77d8d Mon Sep 17 00:00:00 2001 From: Rich Chiodo Date: Tue, 11 Aug 2026 09:58:02 -0700 Subject: [PATCH 1/3] Preserve union-expanded constructor types Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/analyzer/constructors.ts | 34 +++++++++++-------- .../src/analyzer/typeEvaluator.ts | 14 ++++++-- .../src/tests/samples/overloadCall12.py | 32 +++++++++++++++-- 3 files changed, 60 insertions(+), 20 deletions(-) diff --git a/packages/pyright-internal/src/analyzer/constructors.ts b/packages/pyright-internal/src/analyzer/constructors.ts index 20f5907add57..ffbd63c85a21 100644 --- a/packages/pyright-internal/src/analyzer/constructors.ts +++ b/packages/pyright-internal/src/analyzer/constructors.ts @@ -510,30 +510,34 @@ function validateInitMethod( inferenceContext ? { ...inferenceContext, returnTypeOverride } : undefined ); - let adjustedClassType = type; - // Overload evaluation keeps the ordinary __init__ return as a placeholder // and carries argument-dependent constructed types through this separate field, // including when union-expanded argument lists are combined. - if ( - callResult.specializedInitSelfType && - isClassInstance(callResult.specializedInitSelfType) && - ClassType.isSameGenericClass(callResult.specializedInitSelfType, adjustedClassType) - ) { - adjustedClassType = ClassType.cloneAsInstantiable(callResult.specializedInitSelfType); - } + const returnType = callResult.specializedInitSelfType + ? mapSubtypes(callResult.specializedInitSelfType, (specializedInitSelfSubtype) => { + let adjustedClassType = type; + if ( + isClassInstance(specializedInitSelfSubtype) && + ClassType.isSameGenericClass(specializedInitSelfSubtype, adjustedClassType) + ) { + adjustedClassType = ClassType.cloneAsInstantiable(specializedInitSelfSubtype); + } + + if ( + !type.priv.isTypeArgExplicit && + (isAny(specializedInitSelfSubtype) || isUnknown(specializedInitSelfSubtype)) + ) { + return specializedInitSelfSubtype; + } - const returnType = - callResult.specializedInitSelfType && - !type.priv.isTypeArgExplicit && - (isAny(callResult.specializedInitSelfType) || isUnknown(callResult.specializedInitSelfType)) - ? callResult.specializedInitSelfType - : applyExpectedTypeForConstructor( + return applyExpectedTypeForConstructor( evaluator, adjustedClassType, /* inferenceContext */ undefined, constraints ); + }) + : applyExpectedTypeForConstructor(evaluator, type, /* inferenceContext */ undefined, constraints); if (callResult.isTypeIncomplete) { isTypeIncomplete = true; diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator.ts b/packages/pyright-internal/src/analyzer/typeEvaluator.ts index 98606d437998..e9b86524bc6c 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator.ts @@ -9947,11 +9947,13 @@ export function createTypeEvaluator( let isTypeIncomplete = false; const overloadsUsedForCall: FunctionType[] = []; let isDefinitiveMatchFound = false; + let hasInitSelfMaterializationAmbiguity = false; const speculativeNode = getSpeculativeNodeForCall(errorNode); for (let expandedTypesIndex = 0; expandedTypesIndex < expandedArgTypes.length; expandedTypesIndex++) { const overloadsUsedStartIndex = overloadsUsedForCall.length; let matchedOverload: FunctionType | undefined; + let specializedInitSelfType: Type | undefined; const argTypeOverride = expandedArgTypes[expandedTypesIndex]; const hasArgTypeOverride = argTypeOverride.some((a) => a !== undefined); let possibleMatchResults: MatchedOverloadInfo[] = []; @@ -10021,6 +10023,7 @@ export function createTypeEvaluator( } } else { returnTypes.push(callResult.returnType); + specializedInitSelfType = callResult.specializedInitSelfType; isDefinitiveMatchFound = true; break; } @@ -10048,6 +10051,7 @@ export function createTypeEvaluator( // Did the filtering produce a single result? If so, we're done. if (possibleMatchResults.length === 1) { returnTypes.push(possibleMatchResults[0].returnType); + specializedInitSelfType = possibleMatchResults[0].specializedInitSelfType; matchedOverloads = [possibleMatchResults[0]]; } else { const firstArgParamPairs = getOverloadArgParamPairs(possibleMatchResults[0]); @@ -10150,7 +10154,8 @@ export function createTypeEvaluator( // combined, and carry the effective constructed types separately. // validateInitMethod consumes specializedInitSelfType to reconstruct // the constructor result after call validation is complete. - specializedInitSelfTypes.push(returnType); + specializedInitSelfType = returnType; + hasInitSelfMaterializationAmbiguity = true; returnTypes.push(possibleMatchResults[0].returnType); } else { returnTypes.push(returnType); @@ -10158,6 +10163,10 @@ export function createTypeEvaluator( } } + if (specializedInitSelfType) { + specializedInitSelfTypes.push(specializedInitSelfType); + } + if (!matchedOverload) { return { argumentErrors: true, isTypeIncomplete, overloadsUsedForCall }; } @@ -10192,7 +10201,8 @@ export function createTypeEvaluator( returnType: combineTypes(returnTypes), isTypeIncomplete, specializedInitSelfType: - specializedInitSelfTypes.length > 0 + specializedInitSelfTypes.length > 0 && + (hasInitSelfMaterializationAmbiguity || expandedArgTypes.length > 1) ? combineTypes(specializedInitSelfTypes) : finalCallResult.specializedInitSelfType, overloadsUsedForCall, diff --git a/packages/pyright-internal/src/tests/samples/overloadCall12.py b/packages/pyright-internal/src/tests/samples/overloadCall12.py index 3eee9b27fad6..d65d6beeaf24 100644 --- a/packages/pyright-internal/src/tests/samples/overloadCall12.py +++ b/packages/pyright-internal/src/tests/samples/overloadCall12.py @@ -161,6 +161,23 @@ def __init__(self, values: list[Any] | bytes) -> None: pass +class AmbiguousTable(Generic[_T]): + @overload + def __init__(self: "AmbiguousTable[int]", values: list[int]) -> None: ... + + @overload + def __init__(self: "AmbiguousTable[str]", values: list[str]) -> None: ... + + @overload + def __init__(self: "AmbiguousTable[int]", values: set[int]) -> None: ... + + @overload + def __init__(self: "AmbiguousTable[str]", values: set[str]) -> None: ... + + def __init__(self, values: list[Any] | set[Any]) -> None: + pass + + def check_constructors(values_any: list[Any], values_unknown: list, values_int: list[int]) -> None: reveal_type(Table(values_any), expected_text="Any") reveal_type(Table(values_unknown), expected_text="Unknown") @@ -171,9 +188,18 @@ def check_constructors(values_any: list[Any], values_unknown: list, values_int: Table[int](["bad"]) -def check_constructor_union(values_any: list[Any] | bytes, values_unknown: list | bytes) -> None: - reveal_type(Table(values_any), expected_text="Any") - reveal_type(Table(values_unknown), expected_text="Unknown") +def check_constructor_union( + table: Table[Any], + values_any: list[Any] | bytes, + values_unknown: list | bytes, + values_int: list[int] | bytes, + values_gradual: list[Any] | set, +) -> None: + reveal_type(Table(values_any), expected_text="Any | Table[bytes]") + reveal_type(Table(values_unknown), expected_text="Unknown | Table[bytes]") + reveal_type(Table(values_int), expected_text="Table[int] | Table[bytes]") + reveal_type(AmbiguousTable(values_gradual), expected_text="Any | Unknown") + reveal_type(table.__init__(values_any), expected_text="None") @overload From 548b3447f80160518438338797f48e86c509da8d Mon Sep 17 00:00:00 2001 From: Rich Chiodo Date: Tue, 11 Aug 2026 11:41:14 -0700 Subject: [PATCH 2/3] Preserve unspecialized constructor branches Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/analyzer/typeEvaluator.ts | 41 +++++++++++++++---- .../src/tests/samples/overloadCall12.py | 18 ++++++++ 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator.ts b/packages/pyright-internal/src/analyzer/typeEvaluator.ts index e9b86524bc6c..82bb76083af1 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator.ts @@ -9948,12 +9948,13 @@ export function createTypeEvaluator( const overloadsUsedForCall: FunctionType[] = []; let isDefinitiveMatchFound = false; let hasInitSelfMaterializationAmbiguity = false; + let hasSpecializedInitSelfType = false; const speculativeNode = getSpeculativeNodeForCall(errorNode); for (let expandedTypesIndex = 0; expandedTypesIndex < expandedArgTypes.length; expandedTypesIndex++) { const overloadsUsedStartIndex = overloadsUsedForCall.length; let matchedOverload: FunctionType | undefined; - let specializedInitSelfType: Type | undefined; + let effectiveInitSelfType: Type | undefined; const argTypeOverride = expandedArgTypes[expandedTypesIndex]; const hasArgTypeOverride = argTypeOverride.some((a) => a !== undefined); let possibleMatchResults: MatchedOverloadInfo[] = []; @@ -10023,7 +10024,8 @@ export function createTypeEvaluator( } } else { returnTypes.push(callResult.returnType); - specializedInitSelfType = callResult.specializedInitSelfType; + effectiveInitSelfType = getEffectiveOverloadReturnType(matchedOverloadInfo); + hasSpecializedInitSelfType ||= !!callResult.specializedInitSelfType; isDefinitiveMatchFound = true; break; } @@ -10051,7 +10053,8 @@ export function createTypeEvaluator( // Did the filtering produce a single result? If so, we're done. if (possibleMatchResults.length === 1) { returnTypes.push(possibleMatchResults[0].returnType); - specializedInitSelfType = possibleMatchResults[0].specializedInitSelfType; + effectiveInitSelfType = getEffectiveOverloadReturnType(possibleMatchResults[0]); + hasSpecializedInitSelfType ||= !!possibleMatchResults[0].specializedInitSelfType; matchedOverloads = [possibleMatchResults[0]]; } else { const firstArgParamPairs = getOverloadArgParamPairs(possibleMatchResults[0]); @@ -10148,13 +10151,14 @@ export function createTypeEvaluator( } } + effectiveInitSelfType = returnType; if (isInitSelfMaterializationAmbiguity) { // Overloaded __init__ methods normally return None. Preserve that // ordinary return as a placeholder while union-expanded calls are // combined, and carry the effective constructed types separately. // validateInitMethod consumes specializedInitSelfType to reconstruct // the constructor result after call validation is complete. - specializedInitSelfType = returnType; + hasSpecializedInitSelfType = true; hasInitSelfMaterializationAmbiguity = true; returnTypes.push(possibleMatchResults[0].returnType); } else { @@ -10163,8 +10167,8 @@ export function createTypeEvaluator( } } - if (specializedInitSelfType) { - specializedInitSelfTypes.push(specializedInitSelfType); + if (effectiveInitSelfType) { + specializedInitSelfTypes.push(effectiveInitSelfType); } if (!matchedOverload) { @@ -10195,14 +10199,19 @@ export function createTypeEvaluator( isTypeIncomplete = true; } + // Union expansion requires one constructor handoff per expanded argument list. + // Materialization ambiguity requires a combined handoff even when there is only + // one argument list because multiple overload candidates contribute to its result. + const shouldCombineInitSelfTypes = + hasInitSelfMaterializationAmbiguity || (expandedArgTypes.length > 1 && hasSpecializedInitSelfType); + return { argumentErrors: finalCallResult.argumentErrors, anyOrUnknownArg: finalCallResult.anyOrUnknownArg, returnType: combineTypes(returnTypes), isTypeIncomplete, specializedInitSelfType: - specializedInitSelfTypes.length > 0 && - (hasInitSelfMaterializationAmbiguity || expandedArgTypes.length > 1) + specializedInitSelfTypes.length > 0 && shouldCombineInitSelfTypes ? combineTypes(specializedInitSelfTypes) : finalCallResult.specializedInitSelfType, overloadsUsedForCall, @@ -10282,7 +10291,21 @@ export function createTypeEvaluator( } function getEffectiveOverloadReturnType(match: MatchedOverloadInfo): Type { - return match.specializedInitSelfType ?? match.returnType; + if (match.specializedInitSelfType) { + return match.specializedInitSelfType; + } + + const boundToType = match.overload.priv.boundToType; + if (match.overload.shared.name === '__init__' && boundToType && isClassInstance(boundToType)) { + return solveAndApplyConstraints(boundToType, match.constraints, { + replaceUnsolved: { + scopeIds: getTypeVarScopeIds(boundToType), + tupleClassType: getTupleClassType(), + }, + }); + } + + return match.returnType; } function getOverloadArgParamPairs(match: MatchedOverloadInfo): { argType: Type; paramType: Type }[] { diff --git a/packages/pyright-internal/src/tests/samples/overloadCall12.py b/packages/pyright-internal/src/tests/samples/overloadCall12.py index d65d6beeaf24..ef27883dabe7 100644 --- a/packages/pyright-internal/src/tests/samples/overloadCall12.py +++ b/packages/pyright-internal/src/tests/samples/overloadCall12.py @@ -178,6 +178,20 @@ def __init__(self, values: list[Any] | set[Any]) -> None: pass +class PartiallySpecializedTable(Generic[_T]): + @overload + def __init__(self: "PartiallySpecializedTable[int]", values: list[int]) -> None: ... + + @overload + def __init__(self: "PartiallySpecializedTable[str]", values: list[str]) -> None: ... + + @overload + def __init__(self, values: set[_T]) -> None: ... + + def __init__(self, values: list[Any] | set[Any]) -> None: + pass + + def check_constructors(values_any: list[Any], values_unknown: list, values_int: list[int]) -> None: reveal_type(Table(values_any), expected_text="Any") reveal_type(Table(values_unknown), expected_text="Unknown") @@ -194,11 +208,15 @@ def check_constructor_union( values_unknown: list | bytes, values_int: list[int] | bytes, values_gradual: list[Any] | set, + values_partially_specialized: list[Any] | set[float], ) -> None: reveal_type(Table(values_any), expected_text="Any | Table[bytes]") reveal_type(Table(values_unknown), expected_text="Unknown | Table[bytes]") reveal_type(Table(values_int), expected_text="Table[int] | Table[bytes]") reveal_type(AmbiguousTable(values_gradual), expected_text="Any | Unknown") + reveal_type( + PartiallySpecializedTable(values_partially_specialized), expected_text="Any | PartiallySpecializedTable[float]" + ) reveal_type(table.__init__(values_any), expected_text="None") From 225318d91f18e7ccf0aa4ebf8b1c336b21fe3030 Mon Sep 17 00:00:00 2001 From: Rich Chiodo Date: Tue, 11 Aug 2026 12:21:00 -0700 Subject: [PATCH 3/3] Preserve inferred constructor unions Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/analyzer/typeEvaluator.ts | 35 ++++++++++--------- .../src/tests/samples/overloadCall12.py | 13 +++++++ 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator.ts b/packages/pyright-internal/src/analyzer/typeEvaluator.ts index 82bb76083af1..16b3821afb27 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator.ts @@ -9948,7 +9948,7 @@ export function createTypeEvaluator( const overloadsUsedForCall: FunctionType[] = []; let isDefinitiveMatchFound = false; let hasInitSelfMaterializationAmbiguity = false; - let hasSpecializedInitSelfType = false; + let hasEffectiveInitSelfType = false; const speculativeNode = getSpeculativeNodeForCall(errorNode); for (let expandedTypesIndex = 0; expandedTypesIndex < expandedArgTypes.length; expandedTypesIndex++) { @@ -10024,8 +10024,7 @@ export function createTypeEvaluator( } } else { returnTypes.push(callResult.returnType); - effectiveInitSelfType = getEffectiveOverloadReturnType(matchedOverloadInfo); - hasSpecializedInitSelfType ||= !!callResult.specializedInitSelfType; + effectiveInitSelfType = getEffectiveInitSelfType(matchedOverloadInfo); isDefinitiveMatchFound = true; break; } @@ -10053,8 +10052,7 @@ export function createTypeEvaluator( // Did the filtering produce a single result? If so, we're done. if (possibleMatchResults.length === 1) { returnTypes.push(possibleMatchResults[0].returnType); - effectiveInitSelfType = getEffectiveOverloadReturnType(possibleMatchResults[0]); - hasSpecializedInitSelfType ||= !!possibleMatchResults[0].specializedInitSelfType; + effectiveInitSelfType = getEffectiveInitSelfType(possibleMatchResults[0]); matchedOverloads = [possibleMatchResults[0]]; } else { const firstArgParamPairs = getOverloadArgParamPairs(possibleMatchResults[0]); @@ -10151,14 +10149,13 @@ export function createTypeEvaluator( } } - effectiveInitSelfType = returnType; if (isInitSelfMaterializationAmbiguity) { // Overloaded __init__ methods normally return None. Preserve that // ordinary return as a placeholder while union-expanded calls are // combined, and carry the effective constructed types separately. // validateInitMethod consumes specializedInitSelfType to reconstruct // the constructor result after call validation is complete. - hasSpecializedInitSelfType = true; + effectiveInitSelfType = returnType; hasInitSelfMaterializationAmbiguity = true; returnTypes.push(possibleMatchResults[0].returnType); } else { @@ -10169,6 +10166,7 @@ export function createTypeEvaluator( if (effectiveInitSelfType) { specializedInitSelfTypes.push(effectiveInitSelfType); + hasEffectiveInitSelfType = true; } if (!matchedOverload) { @@ -10176,6 +10174,12 @@ export function createTypeEvaluator( } } + // Union expansion requires one constructor handoff per expanded argument list. + // Materialization ambiguity requires a combined handoff even when there is only + // one argument list because multiple overload candidates contribute to its result. + const shouldCombineInitSelfTypes = + hasInitSelfMaterializationAmbiguity || (expandedArgTypes.length > 1 && hasEffectiveInitSelfType); + // We found a match for all of the expanded argument lists. Copy the // resulting type var context back into the caller's type var context. // Use the type var context from the last matched overload because it @@ -10186,7 +10190,9 @@ export function createTypeEvaluator( // And run through the first expanded argument list one more time to // populate the type cache. - const finalConstraints = constraints ?? matchedOverloads[0].constraints; + const finalConstraints = shouldCombineInitSelfTypes + ? matchedOverloads[0].constraints + : constraints ?? matchedOverloads[0].constraints; const finalCallResult = validateArgTypesWithContext( errorNode, matchedOverloads[0].matchResults, @@ -10199,12 +10205,6 @@ export function createTypeEvaluator( isTypeIncomplete = true; } - // Union expansion requires one constructor handoff per expanded argument list. - // Materialization ambiguity requires a combined handoff even when there is only - // one argument list because multiple overload candidates contribute to its result. - const shouldCombineInitSelfTypes = - hasInitSelfMaterializationAmbiguity || (expandedArgTypes.length > 1 && hasSpecializedInitSelfType); - return { argumentErrors: finalCallResult.argumentErrors, anyOrUnknownArg: finalCallResult.anyOrUnknownArg, @@ -10291,10 +10291,13 @@ export function createTypeEvaluator( } function getEffectiveOverloadReturnType(match: MatchedOverloadInfo): Type { + return getEffectiveInitSelfType(match) ?? match.returnType; + } + + function getEffectiveInitSelfType(match: MatchedOverloadInfo): Type | undefined { if (match.specializedInitSelfType) { return match.specializedInitSelfType; } - const boundToType = match.overload.priv.boundToType; if (match.overload.shared.name === '__init__' && boundToType && isClassInstance(boundToType)) { return solveAndApplyConstraints(boundToType, match.constraints, { @@ -10305,7 +10308,7 @@ export function createTypeEvaluator( }); } - return match.returnType; + return undefined; } function getOverloadArgParamPairs(match: MatchedOverloadInfo): { argType: Type; paramType: Type }[] { diff --git a/packages/pyright-internal/src/tests/samples/overloadCall12.py b/packages/pyright-internal/src/tests/samples/overloadCall12.py index ef27883dabe7..b40c3f986baa 100644 --- a/packages/pyright-internal/src/tests/samples/overloadCall12.py +++ b/packages/pyright-internal/src/tests/samples/overloadCall12.py @@ -192,6 +192,17 @@ def __init__(self, values: list[Any] | set[Any]) -> None: pass +class InferredTable(Generic[_T]): + @overload + def __init__(self, values: list[_T]) -> None: ... + + @overload + def __init__(self, values: set[_T]) -> None: ... + + def __init__(self, values: list[Any] | set[Any]) -> None: + pass + + def check_constructors(values_any: list[Any], values_unknown: list, values_int: list[int]) -> None: reveal_type(Table(values_any), expected_text="Any") reveal_type(Table(values_unknown), expected_text="Unknown") @@ -209,6 +220,7 @@ def check_constructor_union( values_int: list[int] | bytes, values_gradual: list[Any] | set, values_partially_specialized: list[Any] | set[float], + values_inferred: list[int] | set[str], ) -> None: reveal_type(Table(values_any), expected_text="Any | Table[bytes]") reveal_type(Table(values_unknown), expected_text="Unknown | Table[bytes]") @@ -217,6 +229,7 @@ def check_constructor_union( reveal_type( PartiallySpecializedTable(values_partially_specialized), expected_text="Any | PartiallySpecializedTable[float]" ) + reveal_type(InferredTable(values_inferred), expected_text="InferredTable[int] | InferredTable[str]") reveal_type(table.__init__(values_any), expected_text="None")