Skip to content

Commit

Permalink
Merge 3a9389d into 397ef7d
Browse files Browse the repository at this point in the history
  • Loading branch information
vthemelis committed Aug 26, 2023
2 parents 397ef7d + 3a9389d commit 1ae4c81
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 5 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
.idea
.tox
.coverage
**/.coverage.*
.cache
.eggs/
*.egg-info/
Expand Down
21 changes: 16 additions & 5 deletions src/typeguard/_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
copy_location,
expr,
fix_missing_locations,
iter_fields,
keyword,
walk,
)
Expand Down Expand Up @@ -498,6 +499,21 @@ def __init__(
self.target_node: FunctionDef | AsyncFunctionDef | None = None
self.target_lineno = target_lineno

def generic_visit(self, node: AST) -> AST:
non_empty_list_fields = []
for field_name, val in iter_fields(node):
if isinstance(val, list) and len(val) > 0:
non_empty_list_fields.append(field_name)

node = super().generic_visit(node)

# Add `pass` to list fields that were optimised away
for field_name in non_empty_list_fields:
if not hasattr(node, field_name) or not getattr(node, field_name):
setattr(node, field_name, [Pass()])

return node

@contextmanager
def _use_memo(
self, node: ClassDef | FunctionDef | AsyncFunctionDef
Expand Down Expand Up @@ -1175,11 +1191,6 @@ def visit_If(self, node: If) -> Any:
"""
self.generic_visit(node)

# Fix empty node body (caused by removal of classes/functions not on the target
# path)
if not node.body:
node.body.append(Pass())

if (
self._memo is self._module_memo
and isinstance(node.test, Name)
Expand Down
47 changes: 47 additions & 0 deletions tests/test_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1523,6 +1523,53 @@ def foo(x: str) -> None:
)


def test_dont_leave_empty_ast_container_nodes_2() -> None:
# Regression test for #352
node = parse(
dedent(
"""
try:
class A:
...
def func():
...
except:
class A:
...
def func():
...
def foo(x: str) -> None:
pass
"""
)
)
TypeguardTransformer(["foo"]).visit(node)
assert (
unparse(node)
== dedent(
"""
try:
pass
except:
pass
def foo(x: str) -> None:
from typeguard import TypeCheckMemo
from typeguard._functions import check_argument_types
memo = TypeCheckMemo(globals(), locals())
check_argument_types('foo', {'x': (x, str)}, memo)
"""
).strip()
)


def test_dont_parse_annotated_2nd_arg() -> None:
# Regression test for #352
node = parse(
Expand Down

0 comments on commit 1ae4c81

Please sign in to comment.