Skip to content

Commit 82b4002

Browse files
authored
Merge pull request #1499 from codeflash-ai/codeflash/optimize-pr1498-2026-02-16T20.49.33
⚡️ Speed up function `_parse_and_collect_imports` by 69% in PR #1498 (`cf-simplify-context-extraction`)
2 parents cc77394 + bfa55cb commit 82b4002

1 file changed

Lines changed: 42 additions & 6 deletions

File tree

codeflash/languages/python/context/code_context_extractor.py

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -553,12 +553,48 @@ def _parse_and_collect_imports(code_context: CodeStringsMarkdown) -> tuple[ast.M
553553
except SyntaxError:
554554
return None
555555
imported_names: dict[str, str] = {}
556-
for node in ast.walk(tree):
557-
if isinstance(node, ast.ImportFrom) and node.module:
558-
for alias in node.names:
559-
if alias.name != "*":
560-
imported_name = alias.asname if alias.asname else alias.name
561-
imported_names[imported_name] = node.module
556+
557+
# Directly iterate over the module body and nested structures instead of ast.walk
558+
# This avoids traversing every single node in the tree
559+
def collect_imports(nodes: list[ast.stmt]) -> None:
560+
for node in nodes:
561+
if isinstance(node, ast.ImportFrom) and node.module:
562+
for alias in node.names:
563+
if alias.name != "*":
564+
imported_name = alias.asname if alias.asname else alias.name
565+
imported_names[imported_name] = node.module
566+
# Recursively check nested structures (function defs, class defs, if statements, etc.)
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"):
584+
collect_imports(node.body)
585+
if hasattr(node, "orelse"):
586+
collect_imports(node.orelse)
587+
if hasattr(node, "finalbody"):
588+
collect_imports(node.finalbody)
589+
if hasattr(node, "handlers"):
590+
for handler in node.handlers:
591+
collect_imports(handler.body)
592+
# Handle match/case statements (Python 3.10+)
593+
elif hasattr(ast, "Match") and isinstance(node, ast.Match):
594+
for case in node.cases:
595+
collect_imports(case.body)
596+
597+
collect_imports(tree.body)
562598
return tree, imported_names
563599

564600

0 commit comments

Comments
 (0)