From 5d7e1f96449f63d9da82fcfe598e4b3da141e38c Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Mon, 16 Mar 2026 19:55:41 +0000 Subject: [PATCH] Optimize _class_has_explicit_init The optimization replaces `isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef))` with direct class identity checks `item.__class__ is ast.FunctionDef or item.__class__ is ast.AsyncFunctionDef`, eliminating tuple allocation and the isinstance method call overhead on every iteration through the class body. Line profiler shows the conditional statement dropped from 460.8 ns/hit to 357.4 ns/hit (22% faster per check), directly driving the 11% overall runtime improvement. The optimization is most effective when scanning classes with many body items that are not init methods, as seen in the 46.7% speedup on the test with 1000 members where init is buried at position 500. --- codeflash/languages/python/context/code_context_extractor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codeflash/languages/python/context/code_context_extractor.py b/codeflash/languages/python/context/code_context_extractor.py index 74b8d904b..01895d9b2 100644 --- a/codeflash/languages/python/context/code_context_extractor.py +++ b/codeflash/languages/python/context/code_context_extractor.py @@ -816,7 +816,7 @@ def _get_class_start_line(class_node: ast.ClassDef) -> int: def _class_has_explicit_init(class_node: ast.ClassDef) -> bool: for item in class_node.body: - if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name == "__init__": + if (item.__class__ is ast.FunctionDef or item.__class__ is ast.AsyncFunctionDef) and item.name == "__init__": return True return False