From cd6f05bbb21a9504ecbed7130baedaa88422aabb Mon Sep 17 00:00:00 2001 From: Vasilis Themelis Date: Sun, 27 Aug 2023 16:59:40 +0100 Subject: [PATCH] Only fill-in empty bodies (#388) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alex Grönholm --- src/typeguard/_transformer.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/typeguard/_transformer.py b/src/typeguard/_transformer.py index ad17120..6b45275 100644 --- a/src/typeguard/_transformer.py +++ b/src/typeguard/_transformer.py @@ -55,7 +55,6 @@ copy_location, expr, fix_missing_locations, - iter_fields, keyword, walk, ) @@ -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