Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rik de Graaff Added broader support for context managers in with statements which swallow exceptions. #2448

Merged
merged 3 commits into from
Oct 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 18 additions & 0 deletions packages/pyright-internal/src/analyzer/typeEvaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14765,6 +14765,22 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions
}
}

if (node.nodeType === ParseNodeType.Call) {
let baseType = getDeclaredCallBaseType(node.leftExpression);
if (!baseType) {
return undefined;
}

if (baseType && isInstantiableClass(baseType)) {
const inst = convertToInstance(baseType);
return inst;
}

if (isFunction(baseType)) {
return baseType.details.declaredReturnType;
}
}

return undefined;
}

Expand Down Expand Up @@ -14822,6 +14838,8 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions
const callType = getDeclaredCallBaseType(node.leftExpression);
if (callType && isInstantiableClass(callType)) {
cmType = convertToInstance(callType);
} else if (callType && isFunction(callType)) {
cmType = callType.details.declaredReturnType;
}
} else if (node.nodeType === ParseNodeType.Name) {
cmType = getDeclaredTypeForExpression(node);
Expand Down
2 changes: 1 addition & 1 deletion packages/pyright-internal/src/tests/checker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ test('With2', () => {
test('With3', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['with3.py']);

TestUtils.validateResults(analysisResults, 3);
TestUtils.validateResults(analysisResults, 4);
});

test('With4', () => {
Expand Down
14 changes: 14 additions & 0 deletions packages/pyright-internal/src/tests/samples/with3.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,17 @@ def test3(cm: suppress) -> None:
# This should generate an error because the
# code is reachable.
return 1

class CMFactory:
def suppress(self) -> suppress:
return suppress()

def test4() -> None:
some_dict = dict()

with CMFactory().suppress():
print(some_dict["missing_key"])

# This should generate an error because the
# code is reachable.
return 1