Changed inference behavior for generator functions with no reachable yield or yield from statements. The "yield type" (the first type argument to Generator) is now inferred as Never in this case rather than None. This addresses #8127. (#8130)

This commit is contained in:
Eric Traut 2024-06-12 09:40:56 -07:00 committed by GitHub
parent 597c634157
commit b0cee14316
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 17 additions and 5 deletions

View File

@ -18679,8 +18679,14 @@ export function createTypeEvaluator(
isClassInstance(iteratorTypeResult.type) &&
ClassType.isBuiltIn(iteratorTypeResult.type, 'Coroutine')
) {
const yieldType =
iteratorTypeResult.type.typeArguments &&
iteratorTypeResult.type.typeArguments.length > 0
? iteratorTypeResult.type.typeArguments[0]
: UnknownType.create();
// Handle old-style (pre-await) Coroutines.
inferredYieldTypes.push();
inferredYieldTypes.push(yieldType);
useAwaitableGenerator = true;
} else {
const yieldType = getTypeOfIterator(
@ -18688,6 +18694,7 @@ export function createTypeEvaluator(
/* isAsync */ false,
yieldNode
)?.type;
inferredYieldTypes.push(yieldType ?? UnknownType.create());
}
} else {
@ -18708,9 +18715,6 @@ export function createTypeEvaluator(
});
}
if (inferredYieldTypes.length === 0) {
inferredYieldTypes.push(getNoneType());
}
const inferredYieldType = combineTypes(inferredYieldTypes);
// Inferred yield types need to be wrapped in a Generator or

View File

@ -17,7 +17,7 @@ async def func1() -> None:
reveal_type(
old_style_coroutine1,
expected_text="() -> AwaitableGenerator[None, Unknown, None, Any]",
expected_text="() -> AwaitableGenerator[Any, Unknown, None, Any]",
)

View File

@ -54,3 +54,11 @@ def consumer3() -> ClassA | None:
print(str)
else:
return value
def generator4():
return
yield 1
reveal_type(generator4(), expected_text="Generator[Never, Any, None]")