Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
38 changes: 35 additions & 3 deletions packages/pyright-internal/src/analyzer/typeGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,31 @@ function narrowTupleTypeForIsNone(evaluator: TypeEvaluator, type: Type, isPositi
});
}

// At runtime, a NewType instance is simply an instance of its base type.
// If the provided type is an instance of a NewType class, this returns the
// underlying base type instance (recursively unwrapping nested NewTypes).
// Otherwise, it returns undefined.
function getNewTypeBaseInstance(type: Type): ClassType | undefined {
if (!isClassInstance(type)) {
return undefined;
}

let current: ClassType = type;
let found = false;

while (ClassType.isNewTypeClass(current) && current.shared.baseClasses.length > 0) {
const baseClass = current.shared.baseClasses[0];
if (!isInstantiableClass(baseClass)) {
break;
}

current = baseClass;
found = true;
}

return found ? ClassType.cloneAsInstance(current) : undefined;
}

Comment thread
rchiodo marked this conversation as resolved.
// Handle type narrowing for expressions of the form "x is None" and "x is not None".
function narrowTypeForIsNone(evaluator: TypeEvaluator, type: Type, isPositiveTest: boolean) {
const expandedType = mapSubtypes(type, (subtype) => {
Expand Down Expand Up @@ -1134,8 +1159,11 @@ function narrowTypeForIsNone(evaluator: TypeEvaluator, type: Type, isPositiveTes
return isPositiveTest ? adjustedSubtype : undefined;
}

// Is it potentially None?
if (evaluator.assignType(subtype, evaluator.getNoneType())) {
// Is it potentially None? For NewType instances, the runtime value
// is an instance of the underlying base type, so test the base type
// for overlap with None.
const subtypeForNoneCheck = getNewTypeBaseInstance(subtype) ?? subtype;
if (evaluator.assignType(subtypeForNoneCheck, evaluator.getNoneType())) {
resultIncludesNoneSubtype = true;
return isPositiveTest
Comment thread
rchiodo marked this conversation as resolved.
? addConditionToType(evaluator.getNoneType(), subtype.props?.condition)
Comment thread
rchiodo marked this conversation as resolved.
Expand Down Expand Up @@ -2741,7 +2769,11 @@ function narrowTypeForLiteralComparison(
}

if (isIsOperator || isNoneInstance(subtype)) {
const isSubtype = evaluator.assignType(subtype, literalType);
// For NewType instances, the runtime value is an instance of the
// underlying base type, so test the base type for overlap with
// the literal.
const subtypeForCheck = getNewTypeBaseInstance(subtype) ?? subtype;
const isSubtype = evaluator.assignType(subtypeForCheck, literalType);
Comment thread
rchiodo marked this conversation as resolved.
Outdated
return isSubtype ? literalType : undefined;
}
}
Expand Down
38 changes: 38 additions & 0 deletions packages/pyright-internal/src/tests/samples/newType8.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# This sample tests narrowing of NewType instances using the "is" operator
# against None and bool literals. At runtime, a NewType instance is simply
# an instance of its base type, so these comparisons can succeed and the
# narrowed branches are reachable.

# pyright: reportUnreachable=true

from types import NoneType
from typing import NewType

Apple = NewType("Apple", NoneType)
Banana = NewType("Banana", bool)
Cherry = NewType("Cherry", int)

# A NewType whose base is itself a NewType (recursive base).
Date = NewType("Date", Apple)


def f(a: Apple, b: Banana, c: Cherry, d: Date) -> None:
if a is None:
reveal_type(a, expected_text="None")

if b is True:
reveal_type(b, expected_text="Literal[True]")

Comment thread
rchiodo marked this conversation as resolved.
Outdated
if c is False:
reveal_type(c, expected_text="Literal[False]")

if d is None:
reveal_type(d, expected_text="None")


def g(c: Cherry) -> None:
# A NewType based on int cannot overlap with None, so this branch
# remains unreachable.
if c is None:
# This should generate an error because the code is unreachable.
reveal_type(c)
Comment thread
rchiodo marked this conversation as resolved.
Outdated
6 changes: 6 additions & 0 deletions packages/pyright-internal/src/tests/typeEvaluator2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,12 @@ test('NewType7', () => {
TestUtils.validateResults(analysisResults, 2);
});

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

TestUtils.validateResults(analysisResults, 1);
});
Comment thread
rchiodo marked this conversation as resolved.

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

Expand Down
Loading