Fixed recent regression relating to "isinstance" type narrowing when the type of the target is a constrained TypeVar.

This commit is contained in:
Eric Traut 2020-07-14 13:56:07 -07:00
parent 174a90c2d7
commit 1cc56a58c2
3 changed files with 27 additions and 8 deletions

View File

@ -469,8 +469,6 @@ export function partiallySpecializeType(type: Type, contextClassType: ClassType)
// Replaces all of the top-level TypeVars (as opposed to TypeVars
// used as type arguments in other types) with their concrete form.
// Unlikely typical TypeVar specialization, this method specializes
// constrained TypeVars as the first constrained type.
export function makeTypeVarsConcrete(type: Type): Type {
return doForSubtypes(type, (subtype) => {
if (subtype.category === TypeCategory.TypeVar) {
@ -478,12 +476,6 @@ export function makeTypeVarsConcrete(type: Type): Type {
return subtype.boundType;
}
// If the type is constrained by more than one type, we can't check
// all constrained types, but we can at least check the first one.
if (subtype.constraints.length > 0) {
return subtype.constraints[0];
}
// Normally, we would use UnknownType here, but we need
// to use Any because unknown types will generate diagnostics
// in strictly-typed files that cannot be suppressed in

View File

@ -1338,6 +1338,12 @@ test('GenericTypes24', () => {
validateResults(analysisResults, 1);
});
test('GenericTypes25', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['genericTypes25.py']);
validateResults(analysisResults, 0);
});
test('Protocol1', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['protocol1.py']);

View File

@ -0,0 +1,21 @@
# This sample tests type narrowing of generic constrained types.
from typing import AnyStr, List, Sequence, Union
Command = Union[AnyStr, Sequence[AnyStr]]
def version1(cmd: Command) -> List[str]:
if isinstance(cmd, bytes):
return [str(cmd, "utf-8")]
if isinstance(cmd, str):
return [cmd]
ret: List[str] = []
for itm in cmd:
if isinstance(itm, str):
ret.append(itm)
else:
ret.append(str(itm, "utf-8"))
return ret