Skip to content

Commit 165b5fb

Browse files
authored
Merge pull request #238 from codeflash-ai/codeflash/optimize-function_has_return_statement-maxgutzd
⚡️ Speed up function `function_has_return_statement` by 90%
2 parents 60af8b7 + 6ac7616 commit 165b5fb

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

codeflash/discovery/functions_to_optimize.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,9 @@ def get_functions_to_optimize(
158158
module_root: Path,
159159
previous_checkpoint_functions: dict[str, dict[str, str]] | None = None,
160160
) -> tuple[dict[Path, list[FunctionToOptimize]], int]:
161-
assert (
162-
sum([bool(optimize_all), bool(replay_test), bool(file)]) <= 1
163-
), "Only one of optimize_all, replay_test, or file should be provided"
161+
assert sum([bool(optimize_all), bool(replay_test), bool(file)]) <= 1, (
162+
"Only one of optimize_all, replay_test, or file should be provided"
163+
)
164164
functions: dict[str, list[FunctionToOptimize]]
165165
with warnings.catch_warnings():
166166
warnings.simplefilter(action="ignore", category=SyntaxWarning)
@@ -207,7 +207,7 @@ def get_functions_to_optimize(
207207
if optimize_all:
208208
three_min_in_ns = int(1.8e11)
209209
logger.info(
210-
f"It might take about {humanize_runtime(functions_count*three_min_in_ns)} to fully optimize this project. Codeflash "
210+
f"It might take about {humanize_runtime(functions_count * three_min_in_ns)} to fully optimize this project. Codeflash "
211211
f"will keep opening pull requests as it finds optimizations."
212212
)
213213
return filtered_modified_functions, functions_count
@@ -539,7 +539,14 @@ def filter_files_optimized(file_path: Path, tests_root: Path, ignore_paths: list
539539

540540

541541
def function_has_return_statement(function_node: FunctionDef | AsyncFunctionDef) -> bool:
542-
return any(isinstance(node, ast.Return) for node in ast.walk(function_node))
542+
# Custom DFS, return True as soon as a Return node is found
543+
stack = [function_node]
544+
while stack:
545+
node = stack.pop()
546+
if isinstance(node, ast.Return):
547+
return True
548+
stack.extend(ast.iter_child_nodes(node))
549+
return False
543550

544551

545552
def function_is_a_property(function_node: FunctionDef | AsyncFunctionDef) -> bool:

0 commit comments

Comments
 (0)