From 6711348cfa23bf422810d9daf3646715096a10d4 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Sat, 19 Oct 2024 14:56:19 -0700 Subject: [PATCH] Fixed recent regression that results in a spurious type error when accessing an instance variable `self.x` if `x` has the type of a class-scoped type variable with a default value. This addresses #9246. --- .../pyright-internal/src/analyzer/typeUtils.ts | 4 +++- .../src/tests/samples/self11.py | 17 +++++++++++++++++ .../src/tests/typeEvaluator8.test.ts | 6 ++++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 packages/pyright-internal/src/tests/samples/self11.py diff --git a/packages/pyright-internal/src/analyzer/typeUtils.ts b/packages/pyright-internal/src/analyzer/typeUtils.ts index 7dce86843a68..b690a4958043 100644 --- a/packages/pyright-internal/src/analyzer/typeUtils.ts +++ b/packages/pyright-internal/src/analyzer/typeUtils.ts @@ -1145,7 +1145,9 @@ export function getUnknownTypeForCallable(): FunctionType { // "self specializes" the class, filling in its own type parameters // as type arguments. export function selfSpecializeClass(type: ClassType, options?: SelfSpecializeOptions): ClassType { - if (!requiresTypeArgs(type)) { + // We can't use requiresTypeArgs(type) here because it returns false + // if the type parameters have default values. + if (type.shared.typeParams.length === 0) { return type; } diff --git a/packages/pyright-internal/src/tests/samples/self11.py b/packages/pyright-internal/src/tests/samples/self11.py new file mode 100644 index 000000000000..4e9941adf20d --- /dev/null +++ b/packages/pyright-internal/src/tests/samples/self11.py @@ -0,0 +1,17 @@ +# This sample tests a case where "self" refers to a class with type +# parameters that have default values. This is a case that regressed. + + +class Base: ... + + +class A(Base): ... + + +class B[T: Base = A]: + def __init__(self, x: T) -> None: + self._x = x + + @property + def x(self) -> T: + return self._x diff --git a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts index 9198c978c2f6..b16742a831e8 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts @@ -689,6 +689,12 @@ test('Self10', () => { TestUtils.validateResults(analysisResults, 2); }); +test('Self11', () => { + const analysisResults = TestUtils.typeAnalyzeSampleFiles(['self11.py']); + + TestUtils.validateResults(analysisResults, 0); +}); + test('UnusedVariable1', () => { const configOptions = new ConfigOptions(Uri.empty());