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

Add support for try blocks in stubs #111

Merged
merged 1 commit into from
Jul 12, 2024
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
9 changes: 9 additions & 0 deletions tests/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,15 @@ def test_dot_import(self) -> None:
names["f"].ast, typeshed_client.ImportedName(path, "f")
)

def test_try(self) -> None:
ctx = get_context((3, 10))
names = get_stub_names("tryexcept", search_context=ctx)
assert names is not None
self.assertEqual(set(names), {"np", "f", "x"})
self.check_nameinfo(names, "np", typeshed_client.ImportedName)
self.check_nameinfo(names, "f", ast.FunctionDef)
self.check_nameinfo(names, "x", ast.AnnAssign)

def check_nameinfo(
self,
names: typeshed_client.NameDict,
Expand Down
1 change: 1 addition & 0 deletions tests/typeshed/VERSIONS
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ about: 3.5-
importabout: 3.5-
tupleall: 3.5-
starimportall: 3.5-
tryexcept: 3.5-
9 changes: 9 additions & 0 deletions tests/typeshed/tryexcept.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
try:
import numpy as np

def f(x: np.int64) -> np.int64: ...

except ImportError:
pass
finally:
x: int
8 changes: 8 additions & 0 deletions typeshed_client/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,14 @@ def visit_If(self, node: ast.If) -> Iterable[NameInfo]:
for stmt in node.orelse:
yield from self.visit(stmt)

def visit_Try(self, node: ast.Try) -> Iterable[NameInfo]:
# try-except sometimes gets used with conditional imports. We assume
# the try block is always executed.
for stmt in node.body:
yield from self.visit(stmt)
for stmt in node.finalbody:
yield from self.visit(stmt)

def visit_Assert(self, node: ast.Assert) -> Iterable[NameInfo]:
visitor = _LiteralEvalVisitor(self.ctx)
value = visitor.visit(node.test)
Expand Down
Loading