Skip to content

Commit

Permalink
Enhanced isinstance narrowing logic to retain type arguments in cas…
Browse files Browse the repository at this point in the history
…es where the filter type (the second argument) is a child of the un-narrowed type and the child has a type parameter that is used multiple times in its base class (e.g. `Child[T](Parent[T, T])`). This addresses #9141. (#9144)
  • Loading branch information
erictraut authored Oct 3, 2024
1 parent 3b8ffed commit cd5f5d3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 18 deletions.
27 changes: 10 additions & 17 deletions packages/pyright-internal/src/analyzer/constraintSolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ import {
TypeVarKind,
TypeVarScopeId,
TypeVarType,
UnknownType,
Variance,
} from './types';
import {
Expand Down Expand Up @@ -476,23 +475,17 @@ export function addConstraintsForExpectedType(
typeArgValue = transformExpectedType(typeArgValue, liveTypeVarScopes, usageOffset);
}

if (typeArgValue) {
const variance = TypeVarType.getVariance(typeVar);

// If this type variable already has a type, don't overwrite it. This can
// happen if a single type variable in the derived class is used multiple times
// in the specialized base class type (e.g. Mapping[T, T]).
if (constraints.getMainConstraintSet().getTypeVar(targetTypeVar)) {
isResultValid = false;
typeArgValue = UnknownType.create();
}

constraints.setBounds(
if (
!typeArgValue ||
!assignTypeVar(
evaluator,
targetTypeVar,
variance === Variance.Covariant ? undefined : typeArgValue,
variance === Variance.Contravariant ? undefined : typeArgValue
);
} else {
typeArgValue,
/* diag */ undefined,
constraints,
AssignTypeFlags.RetainLiteralsForTypeVar
)
) {
isResultValid = false;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ class Sub2(Base2[T, T]):

def func10(val: Sub2[str] | Base2[str, float]):
if isinstance(val, Sub2):
reveal_type(val, expected_text="Sub2[str] | Sub2[Unknown]")
reveal_type(val, expected_text="Sub2[str] | Sub2[str | float]")


@runtime_checkable
Expand Down

0 comments on commit cd5f5d3

Please sign in to comment.