Skip to content

Commit

Permalink
Only fill-in empty bodies (#388)
Browse files Browse the repository at this point in the history
Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi>
  • Loading branch information
vthemelis and agronholm committed Aug 27, 2023
1 parent 3110420 commit cd6f05b
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/typeguard/_transformer.py
Expand Up @@ -55,7 +55,6 @@
copy_location,
expr,
fix_missing_locations,
iter_fields,
keyword,
walk,
)
Expand Down Expand Up @@ -500,17 +499,20 @@ def __init__(
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)
has_non_empty_body_initially = bool(getattr(node, "body", None))
initial_type = type(node)

node = super().generic_visit(node)

# Add `pass` to list fields that were optimised away
for field_name in non_empty_list_fields:
if not getattr(node, field_name, None):
setattr(node, field_name, [Pass()])
if (
type(node) is initial_type
and has_non_empty_body_initially
and hasattr(node, "body")
and not node.body
):
# If we have still the same node type after transformation
# but we've optimised it's body away, we add a `pass` statement.
node.body = [Pass()]

return node

Expand Down

0 comments on commit cd6f05b

Please sign in to comment.