@@ -553,7 +553,7 @@ def _parse_and_collect_imports(code_context: CodeStringsMarkdown) -> tuple[ast.M
553553 except SyntaxError :
554554 return None
555555 imported_names : dict [str , str ] = {}
556-
556+
557557 # Directly iterate over the module body and nested structures instead of ast.walk
558558 # This avoids traversing every single node in the tree
559559 def collect_imports (nodes ):
@@ -564,19 +564,32 @@ def collect_imports(nodes):
564564 imported_name = alias .asname if alias .asname else alias .name
565565 imported_names [imported_name ] = node .module
566566 # Recursively check nested structures (function defs, class defs, if statements, etc.)
567- elif isinstance (node , (ast .FunctionDef , ast .AsyncFunctionDef , ast .ClassDef ,
568- ast .If , ast .For , ast .AsyncFor , ast .While , ast .With ,
569- ast .AsyncWith , ast .Try , ast .ExceptHandler )):
570- if hasattr (node , 'body' ):
567+ elif isinstance (
568+ node ,
569+ (
570+ ast .FunctionDef ,
571+ ast .AsyncFunctionDef ,
572+ ast .ClassDef ,
573+ ast .If ,
574+ ast .For ,
575+ ast .AsyncFor ,
576+ ast .While ,
577+ ast .With ,
578+ ast .AsyncWith ,
579+ ast .Try ,
580+ ast .ExceptHandler ,
581+ ),
582+ ):
583+ if hasattr (node , "body" ):
571584 collect_imports (node .body )
572- if hasattr (node , ' orelse' ):
585+ if hasattr (node , " orelse" ):
573586 collect_imports (node .orelse )
574- if hasattr (node , ' finalbody' ):
587+ if hasattr (node , " finalbody" ):
575588 collect_imports (node .finalbody )
576- if hasattr (node , ' handlers' ):
589+ if hasattr (node , " handlers" ):
577590 for handler in node .handlers :
578591 collect_imports (handler .body )
579-
592+
580593 collect_imports (tree .body )
581594 return tree , imported_names
582595
0 commit comments