Fixed false positive when a TypeVar appears within a function type comment. This addresses #7854. (#7856)

This commit is contained in:
Eric Traut 2024-05-06 21:05:19 -07:00 committed by GitHub
parent e7cc55ad68
commit 377958a0ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 42 additions and 6 deletions

View File

@ -2515,6 +2515,17 @@ export class Checker extends ParseTreeWalker {
nameWalker.walk(node.returnTypeAnnotation);
}
if (node.functionAnnotationComment) {
node.functionAnnotationComment.paramTypeAnnotations.forEach((expr) => {
nameWalker.walk(expr);
});
if (node.functionAnnotationComment.returnTypeAnnotation) {
exemptBoundTypeVar = false;
nameWalker.walk(node.functionAnnotationComment.returnTypeAnnotation);
}
}
localTypeVarUsage.forEach((usage) => {
// Report error for local type variable that appears only once.
if (usage.nodes.length === 1 && !usage.isExempt) {

View File

@ -11,15 +11,15 @@ class ClassA:
foo: str
def method0(self, a, b):
# type: (_T, str, ClassB) -> str
# type: (_T, str, list[_T]) -> str
return self.foo
def method1(self, a, b):
# type: (_T, str, int) -> ClassB
# type: (_T, str, list[_T]) -> ClassB
return ClassB()
# Too many annotations
def method2(self, a, b): # type: (_T, str, int, int) -> str
def method2(self, a, b): # type: (_T, str, int, list[_T]) -> str
return ""
# Too few annotations
@ -33,5 +33,4 @@ class ClassA:
return self.foo
class ClassB:
...
class ClassB: ...

View File

@ -120,3 +120,29 @@ _T2 = TypeVar("_T2", default=int)
class ClassB(Generic[_T2]):
def __init__(self, x: _T2 = ...) -> None: ...
# This should generate an error because _T appears only once.
def f17(
arg, # type: _T
): # type: (...) -> int
return 1
def f18(
arg, # type: _T
): # type: (...) -> _T
return arg
# This should generate an error because _T appears only once.
def f19(
arg,
): # type: (_T) -> int
return 1
def f20(
arg, # type: _T
): # type: (...) -> _T
return arg

View File

@ -814,7 +814,7 @@ test('TypeVar8', () => {
test('TypeVar9', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typeVar9.py']);
TestUtils.validateResults(analysisResults, 11);
TestUtils.validateResults(analysisResults, 13);
});
test('TypeVar10', () => {