Added heuristic to better handle the case where a symbol is imported from two different modules, one in a try block and another in an except block. This pattern can be found in a number of libraries. This addresses https://github.com/microsoft/pyright/issues/4533.

This commit is contained in:
Eric Traut 2023-01-26 10:13:36 -08:00
parent 9eeeaf46c3
commit 8940738e08
3 changed files with 28 additions and 0 deletions

View File

@ -20600,6 +20600,18 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions
declIndexToConsider = index;
}
});
} else {
// Handle the case where there are multiple imports — one of them in
// a try block and one or more in except blocks. In this case, we'll
// use the one in the try block rather than the excepts.
if (decls.length > 1 && decls.every((decl) => decl.type === DeclarationType.Alias)) {
const nonExceptDecls = decls.filter(
(decl) => decl.type === DeclarationType.Alias && !decl.isInExceptSuite
);
if (nonExceptDecls.length === 1) {
declIndexToConsider = decls.findIndex((decl) => decl === nonExceptDecls[0]);
}
}
}
let sawExplicitTypeAlias = false;

View File

@ -0,0 +1,11 @@
# This sample tests the case where a symbol is imported from two different
# sources, one of them in a try block and another in an except block.
try:
from typing import TypedDict
except ImportError:
from typing_extensions import TypedDict
class TD1(TypedDict):
x: int

View File

@ -197,6 +197,11 @@ test('Import14', () => {
assert.strictEqual(analysisResults[1].errors.length, 0);
});
test('Import15', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['import15.py']);
TestUtils.validateResults(analysisResults, 0);
});
test('DunderAll1', () => {
const configOptions = new ConfigOptions('.');