Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for the X is C and X is not C type guard pattern (w… #5544

Merged
merged 1 commit into from
Jul 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/type-concepts-advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ In addition to assignment-based type narrowing, Pyright supports the following t
* `type(x) is T` and `type(x) is not T`
* `type(x) == T` and `type(x) != T`
* `x is E` and `x is not E` (where E is a literal enum or bool)
* `x is C` and `x is not C` (where C is a class)
* `x == L` and `x != L` (where L is an expression that evaluates to a literal type)
* `x.y is None` and `x.y is not None` (where x is a type that is distinguished by a field with a None)
* `x.y is E` and `x.y is not E` (where E is a literal enum or bool and x is a type that is distinguished by a field with a literal type)
Expand Down
62 changes: 60 additions & 2 deletions packages/pyright-internal/src/analyzer/typeGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,12 @@ export function getTypeNarrowingCallback(
}
}

// Look for "X is Y" or "X is not Y" where Y is a an enum or bool literal.
if (isOrIsNotOperator) {
if (ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression)) {
const rightTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
const rightType = rightTypeResult.type;

// Look for "X is Y" or "X is not Y" where Y is a an enum or bool literal.
if (
isClassInstance(rightType) &&
(ClassType.isEnumClass(rightType) || ClassType.isBuiltIn(rightType, 'bool')) &&
Expand All @@ -246,9 +246,19 @@ export function getTypeNarrowingCallback(
};
};
}

// Look for X is <class> or X is not <class>.
if (isInstantiableClass(rightType)) {
return (type: Type) => {
return {
type: narrowTypeForClassComparison(evaluator, type, rightType, adjIsPositiveTest),
isIncomplete: !!rightTypeResult.isIncomplete,
};
};
}
}

// Look for X[<literal>] is <literal> or X[<literal>] is not <literal>
// Look for X[<literal>] is <literal> or X[<literal>] is not <literal>.
if (
testExpression.leftExpression.nodeType === ParseNodeType.Index &&
testExpression.leftExpression.items.length === 1 &&
Expand Down Expand Up @@ -2078,6 +2088,54 @@ function narrowTypeForTypeIs(evaluator: TypeEvaluator, type: Type, classType: Cl
);
}

// Attempts to narrow a type based on a comparison with a class using "is" or
// "is not". This pattern is sometimes used for sentinels.
function narrowTypeForClassComparison(
evaluator: TypeEvaluator,
referenceType: Type,
classType: ClassType,
isPositiveTest: boolean
): Type {
return mapSubtypes(referenceType, (subtype) => {
const concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);

if (isPositiveTest) {
if (isNoneInstance(concreteSubtype)) {
return undefined;
}

if (isClassInstance(concreteSubtype) && TypeBase.isInstance(subtype)) {
return undefined;
}

if (isInstantiableClass(concreteSubtype) && ClassType.isFinal(concreteSubtype)) {
if (
!ClassType.isSameGenericClass(concreteSubtype, classType) &&
!isIsinstanceFilterSuperclass(
evaluator,
concreteSubtype,
classType,
classType,
/* isInstanceCheck */ false
)
) {
return undefined;
}
}
} else {
if (
isInstantiableClass(concreteSubtype) &&
ClassType.isSameGenericClass(classType, concreteSubtype) &&
ClassType.isFinal(classType)
) {
return undefined;
}
}

return subtype;
});
}

// Attempts to narrow a type (make it more constrained) based on a comparison
// (equal or not equal) to a literal value. It also handles "is" or "is not"
// operators if isIsOperator is true.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# This sample tests type narrowing for conditional
# statements of the form X is <class> or X is not <class>.

from typing import Any, TypeVar, final


@final
class A:
...


@final
class B:
...


class C:
...


def func1(x: type[A] | type[B] | None | int):
if x is A:
reveal_type(x, expected_text="type[A]")
else:
reveal_type(x, expected_text="type[B] | int | None")


def func2(x: type[A] | type[B] | None | int, y: type[A]):
if x is not y:
reveal_type(x, expected_text="type[B] | int | None")
else:
reveal_type(x, expected_text="type[A]")


def func3(x: type[A] | type[B] | Any):
if x is A:
reveal_type(x, expected_text="type[A] | Any")
else:
reveal_type(x, expected_text="type[B] | Any")


def func4(x: type[A] | type[B] | type[C]):
if x is C:
reveal_type(x, expected_text="type[C]")
else:
reveal_type(x, expected_text="type[A] | type[B] | type[C]")


T = TypeVar("T")


def func5(x: type[A] | type[B] | type[T]) -> type[A] | type[B] | type[T]:
if x is A:
reveal_type(x, expected_text="type[A] | type[T@func5]")
else:
reveal_type(x, expected_text="type[B] | type[T@func5]")

return x
6 changes: 6 additions & 0 deletions packages/pyright-internal/src/tests/typeEvaluator1.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,12 @@ test('TypeNarrowingIsNone2', () => {
TestUtils.validateResults(analysisResults, 0);
});

test('TypeNarrowingIsClass1', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typeNarrowingIsClass1.py']);

TestUtils.validateResults(analysisResults, 0);
});

test('TypeNarrowingIsNoneTuple1', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typeNarrowingIsNoneTuple1.py']);

Expand Down
Loading