Skip to content

⚡️ Speed up function _class_has_explicit_init by 11% in PR #1839 (codeflash/optimize-pr1838-2026-03-16T19.35.10) - #1841

Closed
codeflash-ai[bot] wants to merge 1 commit into
unstructured-inferencefrom
codeflash/optimize-pr1839-2026-03-16T19.55.38
Closed

⚡️ Speed up function _class_has_explicit_init by 11% in PR #1839 (codeflash/optimize-pr1838-2026-03-16T19.35.10)#1841
codeflash-ai[bot] wants to merge 1 commit into
unstructured-inferencefrom
codeflash/optimize-pr1839-2026-03-16T19.55.38

Conversation

@codeflash-ai

@codeflash-ai codeflash-ai Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

⚡️ This pull request contains optimizations for PR #1839

If you approve this dependent PR, these changes will be merged into the original PR branch codeflash/optimize-pr1838-2026-03-16T19.35.10.

This PR will be automatically closed if the original PR is merged.


📄 11% (0.11x) speedup for _class_has_explicit_init in codeflash/languages/python/context/code_context_extractor.py

⏱️ Runtime : 494 microseconds 444 microseconds (best of 148 runs)

📝 Explanation and details

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.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 1063 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
import ast

import pytest  # used for our unit tests
# import the function under test from the exact module path provided
from codeflash.languages.python.context.code_context_extractor import \
    _class_has_explicit_init

# Large-scale tests

def _make_simple_functiondef(name: str) -> ast.FunctionDef:
    # Helper to create a minimal ast.FunctionDef node with the given name.
    # Use empty arguments and a single pass statement as the body.
    args = ast.arguments(posonlyargs=[], args=[], kwonlyargs=[], kw_defaults=[], defaults=[])
    return ast.FunctionDef(name=name, args=args, body=[ast.Pass()], decorator_list=[])

def test_returns_true_for_class_with_plain_init():
    # Parse a simple class having a direct __init__ method (FunctionDef) at top-level of the class body
    module = ast.parse(
        """
class A:
    def __init__(self):
        pass
"""
    )
    class_node = module.body[0]  # this is an ast.ClassDef
    # The function should detect the top-level FunctionDef named "__init__" and return True
    assert _class_has_explicit_init(class_node) is True # 862ns -> 761ns (13.3% faster)

def test_returns_false_for_class_without_init():
    # Parse a class that has methods but none named "__init__"
    module = ast.parse(
        """
class B:
    def not_init(self):
        pass

    def another(self):
        pass
"""
    )
    class_node = module.body[0]
    # No top-level FunctionDef named "__init__", so should return False
    assert _class_has_explicit_init(class_node) is False # 1.05μs -> 982ns (7.13% faster)

def test_async_init_is_counted_as_explicit_init():
    # An async function named "__init__" should be detected because the implementation checks AsyncFunctionDef as well
    module = ast.parse(
        """
class C:
    async def __init__(self):
        pass
"""
    )
    class_node = module.body[0]
    # AsyncFunctionDef with name "__init__" should make the function return True
    assert _class_has_explicit_init(class_node) is True # 962ns -> 971ns (0.927% slower)

def test_assigning_to_init_name_does_not_count():
    # If __init__ appears as an assigned name (not as a FunctionDef/AsyncFunctionDef), it must NOT be counted
    module = ast.parse(
        """
class D:
    __init__ = 42
"""
    )
    class_node = module.body[0]
    # The only occurrence of "__init__" is as an Assign target, so should return False
    assert _class_has_explicit_init(class_node) is False # 812ns -> 761ns (6.70% faster)

def test_nested_init_inside_if_not_counted():
    # A FunctionDef named "__init__" nested inside an ast.If in the class body is not a direct child of class.body,
    # so the function should NOT find it (it only iterates direct items of class.body).
    module = ast.parse(
        """
class E:
    if True:
        def __init__(self):
            pass
"""
    )
    class_node = module.body[0]
    # Even though a __init__ is created at runtime in the class body, the AST node is nested inside an If node,
    # so the implementation (which only checks direct children) should return False.
    assert _class_has_explicit_init(class_node) is False # 851ns -> 732ns (16.3% faster)

def test_empty_class_has_no_init():
    # An empty class body should result in False
    module = ast.parse(
        """
class Empty:
    pass
"""
    )
    class_node = module.body[0]
    assert _class_has_explicit_init(class_node) is False # 771ns -> 751ns (2.66% faster)

def test_non_class_input_raises_attribute_error():
    # The function expects an ast.ClassDef with a .body attribute. Passing None should raise AttributeError
    with pytest.raises(AttributeError):
        _class_has_explicit_init(None) # 2.83μs -> 2.54μs (11.4% faster)

def test_functiondef_named_similar_but_not_exact_does_not_count():
    # A method named "_init_" or "__init" should not be treated as "__init__"
    module = ast.parse(
        """
class F:
    def _init_(self):
        pass

    def __init(selfx):  # invalid but syntactically allowed name differs from "__init__" (typo)
        pass
"""
    )
    class_node = module.body[0]
    # Note: The second definition actually has name '__init' (missing trailing underscore) — not equal to '__init__'
    # Our check requires exact equality to '__init__', so function should return False.
    assert _class_has_explicit_init(class_node) is False # 1.08μs -> 972ns (11.3% faster)

def test_large_scale_mixture_of_classes_1000():
    # Construct 1000 ast.ClassDef nodes programmatically: even indices have "__init__", odd do not.
    classes = []
    for i in range(1000):
        if i % 2 == 0:
            # include a top-level __init__ method
            body = [_make_simple_functiondef("__init__"), _make_simple_functiondef("other")]
        else:
            # include only other methods
            body = [_make_simple_functiondef("method_%d" % i)]
        cls = ast.ClassDef(
            name=f"Large{i}",
            bases=[],
            keywords=[],
            body=body,
            decorator_list=[],
        )
        classes.append(cls)

    # Now verify the function returns True for even indices and False for odd indices
    for i, cls_node in enumerate(classes):
        expected = (i % 2 == 0)
        # The function must be deterministic and efficient even when called many times
        assert _class_has_explicit_init(cls_node) is expected # 365μs -> 342μs (6.76% faster)

def test_large_class_with_many_members_performance_like():
    # Create a single class with 1000 members where only one of them is a top-level __init__.
    # This checks that scanning across many body elements still correctly finds the __init__.
    body = []
    # add many dummy methods
    for i in range(999):
        body.append(_make_simple_functiondef(f"m{i}"))
    # insert the real __init__ somewhere in the middle
    body.insert(500, _make_simple_functiondef("__init__"))

    big_class = ast.ClassDef(name="Big", bases=[], keywords=[], body=body, decorator_list=[])
    # The function should find the __init__ despite the large number of members
    assert _class_has_explicit_init(big_class) is True # 61.3μs -> 41.8μs (46.7% faster)
import ast

# imports
import pytest
from codeflash.languages.python.context.code_context_extractor import \
    _class_has_explicit_init

def test_class_with_explicit_init():
    """Test that a class with an explicit __init__ method returns True."""
    code = """
class MyClass:
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 992ns -> 851ns (16.6% faster)

def test_class_without_explicit_init():
    """Test that a class without an explicit __init__ method returns False."""
    code = """
class MyClass:
    def some_method(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is False # 901ns -> 791ns (13.9% faster)

def test_class_with_init_and_other_methods():
    """Test that a class with __init__ and other methods returns True."""
    code = """
class MyClass:
    def __init__(self):
        self.x = 1
    
    def method1(self):
        pass
    
    def method2(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 891ns -> 832ns (7.09% faster)

def test_class_with_init_with_parameters():
    """Test that a class with __init__ having parameters returns True."""
    code = """
class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 892ns -> 812ns (9.85% faster)

def test_class_with_init_with_default_parameters():
    """Test that a class with __init__ having default parameters returns True."""
    code = """
class MyClass:
    def __init__(self, x=10, y=20):
        self.x = x
        self.y = y
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 851ns -> 802ns (6.11% faster)

def test_empty_class():
    """Test that an empty class (with pass) returns False."""
    code = """
class MyClass:
    pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is False # 891ns -> 861ns (3.48% faster)

def test_class_with_only_attributes():
    """Test that a class with only class attributes (no methods) returns False."""
    code = """
class MyClass:
    x = 10
    y = 20
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is False # 972ns -> 931ns (4.40% faster)

def test_class_with_async_init():
    """Test that a class with async __init__ method returns True."""
    code = """
class MyClass:
    async def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 972ns -> 992ns (2.02% slower)

def test_class_with_init_and_attributes_mixed():
    """Test that a class with mixed attributes and __init__ returns True."""
    code = """
class MyClass:
    class_var = 10
    
    def __init__(self):
        self.instance_var = 5
    
    another_var = 20
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 1.16μs -> 1.09μs (6.41% faster)

def test_class_with_init_as_last_method():
    """Test that __init__ at the end of class body is correctly detected."""
    code = """
class MyClass:
    def method1(self):
        pass
    
    def method2(self):
        pass
    
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 1.23μs -> 1.11μs (10.8% faster)

def test_class_with_init_as_first_method():
    """Test that __init__ at the beginning of class body is correctly detected."""
    code = """
class MyClass:
    def __init__(self):
        pass
    
    def method1(self):
        pass
    
    def method2(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 882ns -> 791ns (11.5% faster)

def test_class_with_init_in_middle():
    """Test that __init__ in the middle of class body is correctly detected."""
    code = """
class MyClass:
    def method1(self):
        pass
    
    def __init__(self):
        pass
    
    def method2(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 1.06μs -> 961ns (10.5% faster)

def test_class_with_similar_method_name():
    """Test that method names similar to __init__ but not exact do not match."""
    code = """
class MyClass:
    def _init_(self):
        pass
    
    def init(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is False # 1.07μs -> 911ns (17.6% faster)

def test_class_with_multiple_methods_no_init():
    """Test that a class with multiple methods but no __init__ returns False."""
    code = """
class MyClass:
    def method_a(self):
        pass
    
    def method_b(self):
        pass
    
    def method_c(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is False # 1.18μs -> 1.08μs (9.24% faster)

def test_class_with_nested_class_init():
    """Test that nested classes do not affect parent class detection."""
    code = """
class OuterClass:
    class InnerClass:
        def __init__(self):
            pass
    
    def method(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    # The outer class does not have an explicit __init__
    assert _class_has_explicit_init(class_node) is False # 1.10μs -> 1.00μs (9.98% faster)

def test_class_with_nested_class_and_outer_init():
    """Test that outer class __init__ is detected with nested classes present."""
    code = """
class OuterClass:
    def __init__(self):
        pass
    
    class InnerClass:
        def method(self):
            pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 872ns -> 791ns (10.2% faster)

def test_class_with_docstring_and_init():
    """Test that class with docstring and __init__ is correctly detected."""
    code = """
class MyClass:
    \"\"\"This is a class docstring.\"\"\"
    
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 1.43μs -> 1.30μs (10.1% faster)

def test_class_with_decorators():
    """Test that decorators on class do not affect __init__ detection."""
    code = """
@decorator
class MyClass:
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 882ns -> 731ns (20.7% faster)

def test_class_with_decorated_init():
    """Test that decorators on __init__ method do not affect detection."""
    code = """
class MyClass:
    @property
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    # The decorator doesn't matter; if the name is __init__, it's found
    assert _class_has_explicit_init(class_node) is True # 802ns -> 721ns (11.2% faster)

def test_class_with_staticmethod():
    """Test that staticmethod doesn't interfere with __init__ detection."""
    code = """
class MyClass:
    @staticmethod
    def static_method():
        pass
    
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 1.10μs -> 892ns (23.5% faster)

def test_class_with_classmethod():
    """Test that classmethod doesn't interfere with __init__ detection."""
    code = """
class MyClass:
    @classmethod
    def class_method(cls):
        pass
    
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 1.05μs -> 892ns (17.9% faster)

def test_class_with_property():
    """Test that property doesn't interfere with __init__ detection."""
    code = """
class MyClass:
    @property
    def some_property(self):
        return self._value
    
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 1.07μs -> 942ns (13.8% faster)

def test_class_with_varargs_in_init():
    """Test that __init__ with *args is correctly detected."""
    code = """
class MyClass:
    def __init__(self, *args):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 862ns -> 761ns (13.3% faster)

def test_class_with_kwargs_in_init():
    """Test that __init__ with **kwargs is correctly detected."""
    code = """
class MyClass:
    def __init__(self, **kwargs):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 872ns -> 742ns (17.5% faster)

def test_class_with_complex_init_signature():
    """Test that __init__ with complex signature (*args, **kwargs, etc.) is detected."""
    code = """
class MyClass:
    def __init__(self, a, b=5, *args, c=10, **kwargs):
        pass
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 792ns -> 782ns (1.28% faster)

def test_class_with_only_dunder_methods():
    """Test that a class with only dunder methods (no __init__) returns False."""
    code = """
class MyClass:
    def __str__(self):
        return "MyClass"
    
    def __repr__(self):
        return "MyClass()"
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is False # 1.11μs -> 1.05μs (5.80% faster)

def test_class_with_init_and_other_dunder_methods():
    """Test that __init__ is found among other dunder methods."""
    code = """
class MyClass:
    def __str__(self):
        return "MyClass"
    
    def __init__(self):
        pass
    
    def __repr__(self):
        return "MyClass()"
"""
    tree = ast.parse(code)
    class_node = tree.body[0]
    assert _class_has_explicit_init(class_node) is True # 1.11μs -> 1.01μs (9.88% faster)

def test_class_with_many_methods_no_init():
    """Test with a class containing multiple diverse methods but no __init__."""
    method_names_1 = [
        "process_data", "validate_input", "transform_output", "fetch_records",
        "save_state", "load_state", "reset_cache", "initialize_config",
        "shutdown_services", "log_event"
    ]
    code_1 = "class MyClass:\n"
    for name in method_names_1:
        code_1 += f"    def {name}(self):\n        pass\n"
    
    tree_1 = ast.parse(code_1)
    class_node_1 = tree_1.body[0]
    assert _class_has_explicit_init(class_node_1) is False # 1.98μs -> 1.64μs (20.7% faster)

    method_names_2 = [
        "handle_error", "execute_query", "build_response", "parse_json",
        "serialize_xml", "compress_data", "decompress_data", "encrypt_payload"
    ]
    code_2 = "class AnotherClass:\n"
    for name in method_names_2:
        code_2 += f"    def {name}(self):\n        pass\n"
    
    tree_2 = ast.parse(code_2)
    class_node_2 = tree_2.body[0]
    assert _class_has_explicit_init(class_node_2) is False # 1.30μs -> 1.07μs (21.5% faster)

    method_names_3 = [
        "method_a", "method_b", "method_c", "method_d", "method_e"
    ]
    code_3 = "class ThirdClass:\n"
    for name in method_names_3:
        code_3 += f"    def {name}(self):\n        pass\n"
    
    tree_3 = ast.parse(code_3)
    class_node_3 = tree_3.body[0]
    assert _class_has_explicit_init(class_node_3) is False # 1.11μs -> 902ns (23.3% faster)

def test_class_with_many_methods_with_init_first():
    """Test when __init__ is first with diverse methods following."""
    code_1 = """
class FirstClass:
    def __init__(self):
        pass
    def process_data(self):
        pass
    def validate_input(self):
        pass
"""
    tree_1 = ast.parse(code_1)
    class_node_1 = tree_1.body[0]
    assert _class_has_explicit_init(class_node_1) is True # 841ns -> 801ns (4.99% faster)

    code_2 = """
class SecondClass:
    def __init__(self):
        pass
    def transform_output(self):
        pass
    def fetch_records(self):
        pass
    def save_state(self):
        pass
"""
    tree_2 = ast.parse(code_2)
    class_node_2 = tree_2.body[0]
    assert _class_has_explicit_init(class_node_2) is True # 451ns -> 451ns (0.000% faster)

    code_3 = """
class ThirdClass:
    def __init__(self):
        pass
    def load_state(self):
        pass
    def reset_cache(self):
        pass
"""
    tree_3 = ast.parse(code_3)
    class_node_3 = tree_3.body[0]
    assert _class_has_explicit_init(class_node_3) is True # 411ns -> 381ns (7.87% faster)

def test_class_with_many_methods_with_init_last():
    """Test when __init__ is last among diverse methods."""
    methods_1 = ["process_data", "validate_input", "transform_output"]
    code_1 = "class FirstClass:\n"
    for name in methods_1:
        code_1 += f"    def {name}(self):\n        pass\n"
    code_1 += "    def __init__(self):\n        pass\n"
    
    tree_1 = ast.parse(code_1)
    class_node_1 = tree_1.body[0]
    assert _class_has_explicit_init(class_node_1) is True # 1.27μs -> 1.08μs (17.6% faster)

    methods_2 = ["fetch_records", "save_state", "load_state", "reset_cache"]
    code_2 = "class SecondClass:\n"
    for name in methods_2:
        code_2 += f"    def {name}(self):\n        pass\n"
    code_2 += "    def __init__(self):\n        pass\n"
    
    tree_2 = ast.parse(code_2)
    class_node_2 = tree_2.body[0]
    assert _class_has_explicit_init(class_node_2) is True # 962ns -> 841ns (14.4% faster)

    methods_3 = ["initialize_config", "shutdown_services", "log_event", "handle_error", "execute_query"]
    code_3 = "class ThirdClass:\n"
    for name in methods_3:
        code_3 += f"    def {name}(self):\n        pass\n"
    code_3 += "    def __init__(self):\n        pass\n"
    
    tree_3 = ast.parse(code_3)
    class_node_3 = tree_3.body[0]
    assert _class_has_explicit_init(class_node_3) is True # 1.08μs -> 922ns (17.4% faster)

def test_class_with_many_methods_with_init_middle():
    """Test when __init__ is in the middle among diverse methods."""
    first_methods = ["process_data", "validate_input", "transform_output", "fetch_records"]
    second_methods = ["save_state", "load_state", "reset_cache", "initialize_config"]
    
    code_1 = "class FirstClass:\n"
    for name in first_methods:
        code_1 += f"    def {name}(self):\n        pass\n"
    code_1 += "    def __init__(self):\n        pass\n"
    for name in second_methods:
        code_1 += f"    def {name}(self):\n        pass\n"
    
    tree_1 = ast.parse(code_1)
    class_node_1 = tree_1.body[0]
    assert _class_has_explicit_init(class_node_1) is True # 1.40μs -> 1.24μs (12.8% faster)

    first_methods_2 = ["method_a", "method_b"]
    second_methods_2 = ["method_c", "method_d"]
    
    code_2 = "class SecondClass:\n"
    for name in first_methods_2:
        code_2 += f"    def {name}(self):\n        pass\n"
    code_2 += "    def __init__(self):\n        pass\n"
    for name in second_methods_2:
        code_2 += f"    def {name}(self):\n        pass\n"
    
    tree_2 = ast.parse(code_2)
    class_node_2 = tree_2.body[0]
    assert _class_has_explicit_init(class_node_2) is True # 872ns -> 811ns (7.52% faster)

def test_class_with_many_attributes_and_init():
    """Test with many diverse class attributes and an __init__ method."""
    attributes_1 = ["config", "database", "cache", "logger", "settings"]
    code_1 = "class FirstClass:\n"
    for attr in attributes_1:
        code_1 += f"    {attr} = None\n"
    code_1 += "    def __init__(self):\n        pass\n"
    
    tree_1 = ast.parse(code_1)
    class_node_1 = tree_1.body[0]
    assert _class_has_explicit_init(class_node_1) is True # 1.48μs -> 1.43μs (3.56% faster)

    attributes_2 = ["timeout", "retries", "buffer_size", "max_items"]
    code_2 = "class SecondClass:\n"
    for attr in attributes_2:
        code_2 += f"    {attr} = None\n"
    code_2 += "    def __init__(self):\n        pass\n"
    
    tree_2 = ast.parse(code_2)
    class_node_2 = tree_2.body[0]
    assert _class_has_explicit_init(class_node_2) is True # 1.00μs -> 852ns (17.6% faster)

    attributes_3 = ["name", "title", "description"]
    code_3 = "class ThirdClass:\n"
    for attr in attributes_3:
        code_3 += f"    {attr} = None\n"
    code_3 += "    def __init__(self):\n        pass\n"
    
    tree_3 = ast.parse(code_3)
    class_node_3 = tree_3.body[0]
    assert _class_has_explicit_init(class_node_3) is True # 802ns -> 732ns (9.56% faster)

def test_multiple_classes_only_one_with_init():
    """Test detection of __init__ when parsing multiple classes."""
    code = """
class Class1:
    def method(self):
        pass

class Class2:
    def __init__(self):
        pass

class Class3:
    pass
"""
    tree = ast.parse(code)
    
    # Only Class2 should have explicit __init__
    assert _class_has_explicit_init(tree.body[0]) is False # 822ns -> 781ns (5.25% faster)
    assert _class_has_explicit_init(tree.body[1]) is True # 431ns -> 421ns (2.38% faster)
    assert _class_has_explicit_init(tree.body[2]) is False # 460ns -> 471ns (2.34% slower)

def test_deeply_nested_class_structure():
    """Test that function correctly handles deeply nested class definitions."""
    code = """
class Outer:
    class Middle:
        class Inner:
            def __init__(self):
                pass
    
    def __init__(self):
        pass
"""
    tree = ast.parse(code)
    outer_class = tree.body[0]
    
    # Outer class has __init__
    assert _class_has_explicit_init(outer_class) is True # 1.05μs -> 931ns (13.0% faster)
    
    # Middle class (nested) doesn't have __init__ at its level
    middle_class = outer_class.body[0]
    assert _class_has_explicit_init(middle_class) is False # 431ns -> 440ns (2.05% slower)
    
    # Inner class has __init__
    inner_class = middle_class.body[0]
    assert _class_has_explicit_init(inner_class) is True # 380ns -> 401ns (5.24% slower)

def test_class_with_1000_methods():
    """Test with a class containing many diverse methods but no __init__."""
    method_names_batch1 = [
        "process_alpha", "validate_beta", "transform_gamma", "fetch_delta",
        "save_epsilon", "load_zeta", "reset_eta", "initialize_theta"
    ]
    code_1 = "class FirstBatchClass:\n"
    for name in method_names_batch1:
        code_1 += f"    def {name}(self):\n        pass\n"
    
    tree_1 = ast.parse(code_1)
    class_node_1 = tree_1.body[0]
    assert _class_has_explicit_init(class_node_1) is False # 1.79μs -> 1.54μs (16.2% faster)

    method_names_batch2 = [
        "shutdown_iota", "log_kappa", "handle_lambda", "execute_mu",
        "build_nu", "parse_xi", "serialize_omicron", "compress_pi"
    ]
    code_2 = "class SecondBatchClass:\n"
    for name in method_names_batch2:
        code_2 += f"    def {name}(self):\n        pass\n"
    
    tree_2 = ast.parse(code_2)
    class_node_2 = tree_2.body[0]
    assert _class_has_explicit_init(class_node_2) is False # 1.47μs -> 1.20μs (22.5% faster)

    method_names_batch3 = [
        "decompress_rho", "encrypt_sigma", "decrypt_tau", "hash_upsilon",
        "verify_phi", "generate_chi", "revoke_psi", "check_omega"
    ]
    code_3 = "class ThirdBatchClass:\n"
    for name in method_names_batch3:
        code_3 += f"    def {name}(self):\n        pass\n"
    
    tree_3 = ast.parse(code_3)
    class_node_3 = tree_3.body[0]
    assert _class_has_explicit_init(class_node_3) is False # 1.23μs -> 1.01μs (21.7% faster)

def test_class_with_1000_methods_init_at_500():
    """Test when __init__ is at position 100 among diverse methods."""
    first_methods = [
        "process_alpha", "validate_beta", "transform_gamma", "fetch_delta",
        "save_epsilon", "load_zeta", "reset_eta", "initialize_theta",
        "shutdown_iota", "log_kappa"
    ]
    second_methods = [
        "handle_lambda", "execute_mu", "build_nu", "parse_xi",
        "serialize_omicron", "compress_pi"
    ]
    
    code_1 = "class FirstClass:\n"
    for name in first_methods:
        code_1 += f"    def {name}(self):\n        pass\n"
    code_1 += "    def __init__(self):\n        pass\n"
    for name in second_methods:
        code_1 += f"    def {name}(self):\n        pass\n"
    
    tree_1 = ast.parse(code_1)
    class_node_1 = tree_1.body[0]
    assert _class_has_explicit_init(class_node_1) is True # 2.10μs -> 1.79μs (17.3% faster)

    first_batch_2 = ["method_one", "method_two", "method_three"]
    second_batch_2 = ["method_four", "method_five"]
    
    code_2 = "class SecondClass:\n"
    for name in first_batch_2:
        code_2 += f"    def {name}(self):\n        pass\n"
    code_2 += "    def __init__(self):\n        pass\n"
    for name in second_batch_2:
        code_2 += f"    def {name}(self):\n        pass\n"
    
    tree_2 = ast.parse(code_2)
    class_node_2 = tree_2.body[0]
    assert _class_has_explicit_init(class_node_2) is True # 902ns -> 721ns (25.1% faster)

def test_class_with_1000_methods_init_at_end():
    """Test when __init__ is at the end of diverse methods."""
    method_names = [
        "process_alpha", "validate_beta", "transform_gamma", "fetch_delta",
        "save_epsilon", "load_zeta", "reset_eta", "initialize_theta",
        "shutdown_iota", "log_kappa", "handle_lambda", "execute_mu",
        "build_nu", "parse_xi", "serialize_omicron", "compress_pi"
    ]
    code_1 = "class FirstClass:\n"
    for name in method_names:
        code_1 += f"    def {name}(self):\n        pass\n"
    code_1 += "    def __init__(self):\n        pass\n"
    
    tree_1 = ast.parse(code_1)
    class_node_1 = tree_1.body[0]
    assert _class_has_explicit_init(class_node_1) is True # 2.92μs -> 2.38μs (22.7% faster)

    method_names_2 = [
        "decompress_rho", "encrypt_sigma", "decrypt_tau", "hash_upsilon",
        "verify_phi", "generate_chi", "revoke_psi", "check_omega",
        "audit_one", "notify_two", "send_three", "schedule_four"
    ]
    code_2 = "class SecondClass:\n"
    for name in method_names_2:
        code_2 += f"    def {name}(self):\n        pass\n"
    code_2 += "    def __init__(self):\n        pass\n"
    
    tree_2 = ast.parse(code_2)
    class_node_2 = tree_2.body[0]
    assert _class_has_explicit_init(class_node_2) is True # 1.98μs -> 1.55μs (27.8% faster)

To edit these changes git checkout codeflash/optimize-pr1839-2026-03-16T19.55.38 and push.

Codeflash Static Badge

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.
@claude

claude Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

Claude finished @codeflash-ai[bot]'s task in 3m 51s —— View job


PR Review Summary

  • Triage PR scope
  • Run lint/typecheck
  • Resolve stale threads
  • Code review
  • Duplicate detection
  • Test coverage
  • Check other codeflash-ai[bot] PRs

Prek Checks

All prek checks pass (ruff lint + format: ✅).

Code Review

mypy type error — fixed

The optimization changed isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) to item.__class__ is ast.FunctionDef or item.__class__ is ast.AsyncFunctionDef. While this is a valid Python runtime optimization, mypy does not narrow types with __class__ is checks — it only narrows with isinstance. This caused a [attr-defined] error on item.name because item remained typed as ast.stmt (which has no .name attribute), and the type-check-cli CI check was already failing.

Fix applied: Reverted the line back to isinstance, which properly narrows the type to ast.FunctionDef | ast.AsyncFunctionDef and allows safe access to .name. Committed as fix: restore isinstance for mypy type narrowing in _class_has_explicit_init.

Duplicate Detection

No duplicates detected. This function is unique to codeflash/languages/python/context/code_context_extractor.py.

Test Coverage

The PR reports 100% coverage from 1063 generated regression tests. No pre-existing unit tests cover this function directly.

Other codeflash-ai[bot] PRs


Base automatically changed from codeflash/optimize-pr1838-2026-03-16T19.35.10 to codeflash/optimize-pr1660-2026-03-16T19.13.06 March 16, 2026 19:58
Base automatically changed from codeflash/optimize-pr1660-2026-03-16T19.13.06 to unstructured-inference March 16, 2026 19:59
@codeflash-ai codeflash-ai Bot closed this Mar 16, 2026
@codeflash-ai

codeflash-ai Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor Author

This PR has been automatically closed because the original PR #1838 by codeflash-ai[bot] was closed.

@codeflash-ai
codeflash-ai Bot deleted the codeflash/optimize-pr1839-2026-03-16T19.55.38 branch March 16, 2026 19:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants