Skip to content

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Nov 12, 2025

📄 29% (0.29x) speedup for Seq._is_seq in src/bokeh/core/property/container.py

⏱️ Runtime : 891 microseconds 692 microseconds (best of 192 runs)

📝 Explanation and details

The optimization restructures the type checking logic in _is_seq and _is_seq_like methods to achieve a 28% speedup by reducing unnecessary expensive operations.

Key optimizations:

  1. Fast string rejection in _is_seq: Instead of evaluating a complex boolean expression with isinstance(value, str) at the end, the optimized version checks for strings first and returns False immediately. This eliminates the need to evaluate isinstance(value, Sequence) or call _is_seq_like() for the common case of string inputs.

  2. Early exit pattern: The optimized version uses early returns (if isinstance(value, str): return False) rather than a single complex boolean expression, allowing the CPU to skip subsequent checks when earlier conditions are met.

  3. Reordered checks in _is_seq_like: The hasattr(value, "__getitem__") check is moved first because it's the fastest operation and rules out most non-sequence types (like sets) immediately. The isinstance(value, Mapping) check follows, avoiding expensive MRO traversal when __getitem__ isn't even present.

Why this is faster:

  • Reduced isinstance calls: String inputs (which are common based on test cases) now only require one isinstance check instead of potentially three.
  • Short-circuiting: Early returns prevent unnecessary execution of expensive type checking operations.
  • Optimized check ordering: The fastest checks (hasattr, then isinstance(Mapping)) happen first, filtering out most cases before the more expensive isinstance(Container, Sized, Iterable) check.

Performance gains by test case type:

  • String inputs: Massive improvements (382-865% faster) due to immediate rejection
  • Non-sequence types (sets, dicts, primitives): 25-90% faster due to early exits in _is_seq_like
  • Actual sequences: Mostly unchanged or slightly faster (0-25% improvement)
  • Custom sequence-like objects: Minimal impact since they still need full evaluation

The optimization maintains identical behavior while significantly reducing computational overhead for the most common rejection cases.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 85 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime
from collections.abc import Container, Iterable, Mapping, Sequence, Sized

# imports
import pytest
from bokeh.core.property.container import Seq

# ------------------- Unit Tests for Seq._is_seq -------------------

# 1. BASIC TEST CASES

def test_list_is_seq():
    # Standard Python list
    codeflash_output = Seq._is_seq([1, 2, 3]) # 1.08μs -> 1.12μs (3.65% slower)

def test_tuple_is_seq():
    # Standard Python tuple
    codeflash_output = Seq._is_seq((1, 2, 3)) # 2.47μs -> 2.41μs (2.32% faster)

def test_empty_list_is_seq():
    # Empty list should still be a sequence
    codeflash_output = Seq._is_seq([]) # 886ns -> 896ns (1.12% slower)

def test_empty_tuple_is_seq():
    # Empty tuple should still be a sequence
    codeflash_output = Seq._is_seq(()) # 2.15μs -> 1.73μs (24.4% faster)

def test_range_is_seq():
    # range is a Sequence
    codeflash_output = Seq._is_seq(range(10)) # 1.95μs -> 1.66μs (17.5% faster)

def test_str_is_not_seq():
    # Strings are Sequences but must be excluded
    codeflash_output = Seq._is_seq("abc") # 1.89μs -> 392ns (382% faster)

def test_bytes_is_not_seq():
    # Bytes are also Sequences but must be excluded
    codeflash_output = Seq._is_seq(b"abc") # 903ns -> 837ns (7.89% faster)

def test_bytearray_is_not_seq():
    # Bytearray is a Sequence but must be excluded
    codeflash_output = Seq._is_seq(bytearray(b"abc")) # 967ns -> 900ns (7.44% faster)

def test_list_of_strings_is_seq():
    # List containing strings is still a sequence
    codeflash_output = Seq._is_seq(["a", "b", "c"]) # 915ns -> 883ns (3.62% faster)

def test_nested_list_is_seq():
    # Nested list is a sequence
    codeflash_output = Seq._is_seq([[1, 2], [3, 4]]) # 832ns -> 834ns (0.240% slower)

def test_singleton_list_is_seq():
    # List with one element
    codeflash_output = Seq._is_seq([42]) # 780ns -> 746ns (4.56% faster)

# 2. EDGE TEST CASES

def test_dict_is_not_seq():
    # Dict is a Mapping, not a Sequence
    codeflash_output = Seq._is_seq({"a": 1, "b": 2}) # 2.78μs -> 1.99μs (39.8% faster)

def test_set_is_not_seq():
    # Set is not a Sequence (no __getitem__)
    codeflash_output = Seq._is_seq({1, 2, 3}) # 1.96μs -> 1.46μs (33.6% faster)

def test_frozenset_is_not_seq():
    # Frozenset is not a Sequence
    codeflash_output = Seq._is_seq(frozenset([1, 2])) # 1.86μs -> 1.37μs (36.0% faster)

def test_none_is_not_seq():
    # None should not be considered a sequence
    codeflash_output = Seq._is_seq(None) # 2.24μs -> 1.17μs (91.2% faster)

def test_integer_is_not_seq():
    # Integers are not Sequences
    codeflash_output = Seq._is_seq(123) # 1.97μs -> 1.22μs (61.6% faster)

def test_float_is_not_seq():
    # Floats are not Sequences
    codeflash_output = Seq._is_seq(3.14) # 1.98μs -> 1.39μs (42.6% faster)

def test_bool_is_not_seq():
    # Booleans are not Sequences
    codeflash_output = Seq._is_seq(True) # 2.01μs -> 1.28μs (56.9% faster)

def test_object_with_getitem_and_container_sized_iterable_not_mapping():
    # Custom object that looks like a sequence but isn't a Mapping
    class FakeSeq:
        def __len__(self): return 2
        def __getitem__(self, idx): return idx
        def __contains__(self, item): return item in (0, 1)
        def __iter__(self): return iter([0, 1])
    codeflash_output = Seq._is_seq(FakeSeq()) # 44.4μs -> 43.5μs (2.05% faster)

def test_object_with_getitem_but_is_mapping():
    # Custom Mapping should not be considered a sequence
    class FakeMapping(Mapping):
        def __getitem__(self, key): return 1
        def __iter__(self): return iter([])
        def __len__(self): return 0
    codeflash_output = Seq._is_seq(FakeMapping()) # 15.8μs -> 13.1μs (20.5% faster)

def test_object_with_container_sized_iterable_but_no_getitem():
    # Custom object that's Container, Sized, Iterable but lacks __getitem__
    class AlmostSeq:
        def __len__(self): return 2
        def __contains__(self, item): return False
        def __iter__(self): return iter([1, 2])
    codeflash_output = Seq._is_seq(AlmostSeq()) # 12.9μs -> 10.6μs (22.0% faster)

def test_bytes_subclass_is_not_seq():
    # Subclass of bytes should still be excluded
    class MyBytes(bytes):
        pass
    codeflash_output = Seq._is_seq(MyBytes(b"abc")) # 5.04μs -> 4.90μs (2.94% faster)

def test_str_subclass_is_not_seq():
    # Subclass of str should still be excluded
    class MyStr(str):
        pass
    codeflash_output = Seq._is_seq(MyStr("abc")) # 3.52μs -> 400ns (779% faster)

def test_custom_sequence_subclass():
    # Subclass of list should be accepted
    class MyList(list):
        pass
    codeflash_output = Seq._is_seq(MyList([1, 2, 3])) # 6.47μs -> 6.71μs (3.56% slower)

def test_custom_tuple_subclass():
    # Subclass of tuple should be accepted
    class MyTuple(tuple):
        pass
    codeflash_output = Seq._is_seq(MyTuple((1, 2, 3))) # 2.99μs -> 2.92μs (2.36% faster)

def test_custom_sequence_with_str_repr():
    # Custom object that is a Sequence but has str representation
    class WeirdSeq(list):
        def __str__(self): return "not a sequence"
    codeflash_output = Seq._is_seq(WeirdSeq([1, 2])) # 6.45μs -> 6.36μs (1.29% faster)



def test_iterable_not_sized_not_seq():
    # Iterable but not Sized/Container or Sequence
    class OnlyIterable:
        def __iter__(self): return iter([1, 2])
    codeflash_output = Seq._is_seq(OnlyIterable()) # 65.7μs -> 13.4μs (390% faster)

def test_sequence_with_str_inside():
    # List containing a string is still a sequence
    codeflash_output = Seq._is_seq([1, "a", 3]) # 913ns -> 862ns (5.92% faster)

# 3. LARGE SCALE TEST CASES

def test_large_list_is_seq():
    # Large list (under 1000 elements)
    large = list(range(999))
    codeflash_output = Seq._is_seq(large) # 853ns -> 873ns (2.29% slower)

def test_large_tuple_is_seq():
    # Large tuple (under 1000 elements)
    large = tuple(range(999))
    codeflash_output = Seq._is_seq(large) # 2.23μs -> 1.92μs (16.3% faster)

def test_large_range_is_seq():
    # Large range
    large = range(0, 999)
    codeflash_output = Seq._is_seq(large) # 1.95μs -> 1.55μs (25.7% faster)

def test_large_custom_sequence():
    # Custom sequence with 999 elements
    class BigSeq:
        def __init__(self, n):
            self._n = n
        def __len__(self): return self._n
        def __getitem__(self, idx):
            if 0 <= idx < self._n: return idx
            raise IndexError()
        def __contains__(self, item): return 0 <= item < self._n
        def __iter__(self): return iter(range(self._n))
    bigseq = BigSeq(999)
    codeflash_output = Seq._is_seq(bigseq) # 42.0μs -> 42.1μs (0.204% slower)

def test_large_set_is_not_seq():
    # Large set is not a sequence
    large_set = set(range(999))
    codeflash_output = Seq._is_seq(large_set) # 2.03μs -> 1.37μs (47.7% faster)

def test_large_dict_is_not_seq():
    # Large dict is not a sequence
    large_dict = {i: i for i in range(999)}
    codeflash_output = Seq._is_seq(large_dict) # 2.39μs -> 1.74μs (36.9% faster)

def test_large_list_of_strings_is_seq():
    # Large list of strings
    large = ["a"] * 999
    codeflash_output = Seq._is_seq(large) # 909ns -> 911ns (0.220% slower)

def test_large_nested_list_is_seq():
    # Large nested list
    large = [[i] for i in range(999)]
    codeflash_output = Seq._is_seq(large) # 935ns -> 971ns (3.71% slower)

# 4. ADDITIONAL EDGE CASES

def test_empty_string_is_not_seq():
    # Empty string is not a sequence
    codeflash_output = Seq._is_seq("") # 2.26μs -> 375ns (503% faster)

def test_empty_bytes_is_not_seq():
    # Empty bytes is not a sequence
    codeflash_output = Seq._is_seq(b"") # 896ns -> 888ns (0.901% faster)

def test_empty_bytearray_is_not_seq():
    # Empty bytearray is not a sequence
    codeflash_output = Seq._is_seq(bytearray()) # 930ns -> 863ns (7.76% faster)

def test_empty_set_is_not_seq():
    # Empty set is not a sequence
    codeflash_output = Seq._is_seq(set()) # 2.10μs -> 1.47μs (43.5% faster)

def test_empty_dict_is_not_seq():
    # Empty dict is not a sequence
    codeflash_output = Seq._is_seq({}) # 2.34μs -> 1.84μs (26.7% faster)

def test_object_with_str_and_getitem_but_not_container_sized_iterable():
    # Has __getitem__ and __str__, but not Container/Sized/Iterable
    class OddObject:
        def __getitem__(self, idx): return idx
        def __str__(self): return "Odd"
    codeflash_output = Seq._is_seq(OddObject()) # 78.8μs -> 80.1μs (1.58% slower)

def test_object_with_container_and_sized_but_no_getitem():
    # Has Container and Sized, but no __getitem__
    class NoGetitem(Container, Sized):
        def __len__(self): return 1
        def __contains__(self, item): return False
    codeflash_output = Seq._is_seq(NoGetitem()) # 14.2μs -> 12.2μs (16.8% faster)

def test_object_with_getitem_and_mapping():
    # Has __getitem__ and is Mapping
    class MyMapping(dict):
        pass
    codeflash_output = Seq._is_seq(MyMapping()) # 15.6μs -> 13.5μs (15.1% faster)

def test_object_with_getitem_and_not_container_sized_iterable():
    # Has __getitem__ but not Container/Sized/Iterable
    class OnlyGetitem:
        def __getitem__(self, idx): return idx
    codeflash_output = Seq._is_seq(OnlyGetitem()) # 72.7μs -> 72.2μs (0.663% faster)

def test_object_with_getitem_and_iterable_and_sized_but_is_mapping():
    # Is Mapping, so must not be sequence
    class MyMap(Mapping):
        def __getitem__(self, key): return 1
        def __iter__(self): return iter([])
        def __len__(self): return 0
    codeflash_output = Seq._is_seq(MyMap()) # 15.3μs -> 12.8μs (19.6% faster)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
from collections.abc import Container, Iterable, Mapping, Sequence, Sized

# imports
import pytest
from bokeh.core.property.container import Seq

# ------------------------
# Basic Test Cases
# ------------------------

def test_list_is_seq():
    # Standard list should be recognized as a sequence
    codeflash_output = Seq._is_seq([1, 2, 3]) # 894ns -> 933ns (4.18% slower)

def test_tuple_is_seq():
    # Tuple is a sequence
    codeflash_output = Seq._is_seq((1, 2, 3)) # 2.15μs -> 1.82μs (18.1% faster)

def test_empty_list_is_seq():
    # Empty list is still a sequence
    codeflash_output = Seq._is_seq([]) # 857ns -> 880ns (2.61% slower)

def test_empty_tuple_is_seq():
    # Empty tuple is still a sequence
    codeflash_output = Seq._is_seq(()) # 2.04μs -> 1.77μs (15.2% faster)

def test_range_is_seq():
    # range is a sequence
    codeflash_output = Seq._is_seq(range(10)) # 1.85μs -> 1.60μs (15.5% faster)

def test_bytearray_is_seq():
    # bytearray is a sequence
    codeflash_output = Seq._is_seq(bytearray(b"abc")) # 929ns -> 859ns (8.15% faster)


def test_str_is_not_seq():
    # String is a sequence, but should be excluded
    codeflash_output = Seq._is_seq("abc") # 1.80μs -> 373ns (382% faster)

def test_bytes_is_not_seq():
    # bytes is a sequence, but should be excluded (since not str, but often treated like one)
    codeflash_output = Seq._is_seq(b"abc") # 909ns -> 857ns (6.07% faster)

def test_list_of_strings_is_seq():
    # List of strings is a sequence
    codeflash_output = Seq._is_seq(["a", "b", "c"]) # 879ns -> 869ns (1.15% faster)

def test_nested_list_is_seq():
    # Nested list is a sequence
    codeflash_output = Seq._is_seq([[1, 2], [3, 4]]) # 792ns -> 809ns (2.10% slower)

# ------------------------
# Edge Test Cases
# ------------------------

def test_set_is_not_seq():
    # Set is not a sequence
    codeflash_output = Seq._is_seq({1, 2, 3}) # 2.13μs -> 1.59μs (34.0% faster)

def test_dict_is_not_seq():
    # Dict is not a sequence
    codeflash_output = Seq._is_seq({"a": 1, "b": 2}) # 2.35μs -> 1.85μs (26.9% faster)

def test_none_is_not_seq():
    # None is not a sequence
    codeflash_output = Seq._is_seq(None) # 2.17μs -> 1.17μs (85.7% faster)

def test_int_is_not_seq():
    # Integer is not a sequence
    codeflash_output = Seq._is_seq(42) # 1.90μs -> 1.27μs (49.3% faster)

def test_float_is_not_seq():
    # Float is not a sequence
    codeflash_output = Seq._is_seq(3.14) # 1.98μs -> 1.19μs (66.3% faster)

def test_object_with_getitem_and_sized_and_iterable():
    # Custom sequence-like object should be accepted
    class MySeq:
        def __getitem__(self, idx): return idx if idx < 3 else (_ for _ in ()).throw(IndexError)
        def __len__(self): return 3
        def __iter__(self): return iter([1, 2, 3])
        def __contains__(self, item): return item in [1, 2, 3]
    codeflash_output = Seq._is_seq(MySeq()) # 43.6μs -> 43.3μs (0.679% faster)

def test_object_with_getitem_but_not_sized():
    # Object with __getitem__ but not __len__ is not Sized, but may still be recognized
    class MySeq:
        def __getitem__(self, idx): return idx if idx < 3 else (_ for _ in ()).throw(IndexError)
        def __iter__(self): return iter([1, 2, 3])
        def __contains__(self, item): return item in [1, 2, 3]
    codeflash_output = Seq._is_seq(MySeq()) # 33.5μs -> 33.3μs (0.444% faster)

def test_object_with_getitem_but_mapping():
    # Mapping should be excluded even if it has __getitem__
    class MyMap(Mapping):
        def __getitem__(self, k): return 1
        def __iter__(self): return iter(["a"])
        def __len__(self): return 1
    codeflash_output = Seq._is_seq(MyMap()) # 14.7μs -> 12.3μs (19.4% faster)

def test_object_with_container_sized_iterable_but_no_getitem():
    # Should not be recognized as sequence without __getitem__
    class NoGetitem:
        def __len__(self): return 3
        def __iter__(self): return iter([1, 2, 3])
        def __contains__(self, item): return item in [1, 2, 3]
    codeflash_output = Seq._is_seq(NoGetitem()) # 12.4μs -> 10.7μs (15.9% faster)

def test_object_with_getitem_but_is_str_subclass():
    # Subclass of str should still be excluded
    class MyStr(str): pass
    codeflash_output = Seq._is_seq(MyStr("abc")) # 3.52μs -> 414ns (751% faster)

def test_object_with_getitem_but_is_bytes_subclass():
    # Subclass of bytes should be accepted (since not str)
    class MyBytes(bytes): pass
    codeflash_output = Seq._is_seq(MyBytes(b"abc")) # 5.02μs -> 5.30μs (5.32% slower)

def test_object_with_getitem_and_mapping_but_not_mapping_instance():
    # Object with __getitem__ and __iter__ but not a Mapping instance
    class NotAMapping:
        def __getitem__(self, idx): return idx
        def __iter__(self): return iter([1, 2, 3])
        def __len__(self): return 3
        def __contains__(self, item): return item in [1, 2, 3]
    codeflash_output = Seq._is_seq(NotAMapping()) # 39.6μs -> 40.0μs (1.21% slower)

def test_object_with_only_iterable():
    # Only __iter__, not a sequence
    class OnlyIterable:
        def __iter__(self): return iter([1, 2, 3])
    codeflash_output = Seq._is_seq(OnlyIterable()) # 65.5μs -> 11.1μs (488% faster)

def test_object_with_only_container():
    # Only __contains__, not a sequence
    class OnlyContainer:
        def __contains__(self, item): return False
    codeflash_output = Seq._is_seq(OnlyContainer()) # 13.2μs -> 10.4μs (26.3% faster)

def test_object_with_only_sized():
    # Only __len__, not a sequence
    class OnlySized:
        def __len__(self): return 3
    codeflash_output = Seq._is_seq(OnlySized()) # 45.3μs -> 10.1μs (348% faster)

def test_object_with_getitem_and_mapping_base():
    # Direct Mapping subclass should be excluded
    class MyMapping(Mapping):
        def __getitem__(self, k): return 1
        def __iter__(self): return iter(["a"])
        def __len__(self): return 1
    codeflash_output = Seq._is_seq(MyMapping()) # 14.5μs -> 12.0μs (21.0% faster)

def test_object_with_getitem_and_str_and_mapping():
    # Subclass both str and Mapping -- should be excluded
    class Weird(str, Mapping):
        def __getitem__(self, k): return 1
        def __iter__(self): return iter(["a"])
        def __len__(self): return 1
    codeflash_output = Seq._is_seq(Weird("abc")) # 3.89μs -> 403ns (865% faster)

# ------------------------
# Large Scale Test Cases
# ------------------------

def test_large_list_is_seq():
    # Large list (up to 1000 elements)
    big_list = list(range(1000))
    codeflash_output = Seq._is_seq(big_list) # 959ns -> 927ns (3.45% faster)

def test_large_tuple_is_seq():
    # Large tuple
    big_tuple = tuple(range(1000))
    codeflash_output = Seq._is_seq(big_tuple) # 2.14μs -> 1.98μs (7.87% faster)

def test_large_range_is_seq():
    # Large range
    big_range = range(1000)
    codeflash_output = Seq._is_seq(big_range) # 1.92μs -> 1.68μs (14.1% faster)

def test_large_custom_seq():
    # Custom sequence with 1000 elements
    class BigSeq:
        def __getitem__(self, idx):
            if 0 <= idx < 1000: return idx
            raise IndexError
        def __len__(self): return 1000
        def __iter__(self): return iter(range(1000))
        def __contains__(self, item): return 0 <= item < 1000
    big_seq = BigSeq()
    codeflash_output = Seq._is_seq(big_seq) # 41.9μs -> 40.1μs (4.70% faster)

def test_large_set_is_not_seq():
    # Large set is not a sequence
    big_set = set(range(1000))
    codeflash_output = Seq._is_seq(big_set) # 1.96μs -> 1.55μs (26.2% faster)

def test_large_dict_is_not_seq():
    # Large dict is not a sequence
    big_dict = {i: i for i in range(1000)}
    codeflash_output = Seq._is_seq(big_dict) # 2.33μs -> 1.88μs (24.2% faster)

def test_large_list_of_strings_is_seq():
    # Large list of strings
    big_str_list = ["x"] * 1000
    codeflash_output = Seq._is_seq(big_str_list) # 892ns -> 905ns (1.44% slower)

def test_large_custom_non_seq():
    # Custom object with __iter__ and __len__ but no __getitem__
    class NotSeq:
        def __len__(self): return 1000
        def __iter__(self): return iter(range(1000))
        def __contains__(self, item): return 0 <= item < 1000
    not_seq = NotSeq()
    codeflash_output = Seq._is_seq(not_seq) # 16.2μs -> 13.9μs (16.6% faster)

# ------------------------
# Additional edge cases for mutation testing
# ------------------------

def test_bool_is_not_seq():
    # bool is not a sequence
    codeflash_output = Seq._is_seq(True) # 2.31μs -> 1.36μs (69.4% faster)

def test_frozenset_is_not_seq():
    # frozenset is not a sequence
    codeflash_output = Seq._is_seq(frozenset([1, 2, 3])) # 1.87μs -> 1.37μs (37.0% faster)

def test_object_with_getitem_and_str_but_not_str_instance():
    # Custom object with __getitem__ and __str__ but not a string
    class FakeStr:
        def __getitem__(self, idx): return idx
        def __str__(self): return "not a str"
        def __len__(self): return 3
        def __iter__(self): return iter([1, 2, 3])
        def __contains__(self, item): return item in [1, 2, 3]
    codeflash_output = Seq._is_seq(FakeStr()) # 41.1μs -> 41.0μs (0.276% faster)

def test_bytes_is_seq():
    # bytes is a sequence and not str, so should be True
    codeflash_output = Seq._is_seq(b"abc") # 909ns -> 903ns (0.664% faster)

def test_memoryview_is_seq():
    # memoryview is a sequence and not str, so should be True
    codeflash_output = Seq._is_seq(memoryview(b"abc")) # 2.01μs -> 1.57μs (27.6% faster)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
from bokeh.core.property.container import Seq

def test_Seq__is_seq():
    Seq._is_seq(Seq, ())

To edit these changes git checkout codeflash/optimize-Seq._is_seq-mhwhbouy and push.

Codeflash Static Badge

The optimization restructures the type checking logic in `_is_seq` and `_is_seq_like` methods to achieve a **28% speedup** by reducing unnecessary expensive operations.

**Key optimizations:**

1. **Fast string rejection in `_is_seq`**: Instead of evaluating a complex boolean expression with `isinstance(value, str)` at the end, the optimized version checks for strings first and returns `False` immediately. This eliminates the need to evaluate `isinstance(value, Sequence)` or call `_is_seq_like()` for the common case of string inputs.

2. **Early exit pattern**: The optimized version uses early returns (`if isinstance(value, str): return False`) rather than a single complex boolean expression, allowing the CPU to skip subsequent checks when earlier conditions are met.

3. **Reordered checks in `_is_seq_like`**: The `hasattr(value, "__getitem__")` check is moved first because it's the fastest operation and rules out most non-sequence types (like sets) immediately. The `isinstance(value, Mapping)` check follows, avoiding expensive MRO traversal when `__getitem__` isn't even present.

**Why this is faster:**
- **Reduced `isinstance` calls**: String inputs (which are common based on test cases) now only require one `isinstance` check instead of potentially three.
- **Short-circuiting**: Early returns prevent unnecessary execution of expensive type checking operations.
- **Optimized check ordering**: The fastest checks (`hasattr`, then `isinstance(Mapping)`) happen first, filtering out most cases before the more expensive `isinstance(Container, Sized, Iterable)` check.

**Performance gains by test case type:**
- **String inputs**: Massive improvements (382-865% faster) due to immediate rejection
- **Non-sequence types** (sets, dicts, primitives): 25-90% faster due to early exits in `_is_seq_like`
- **Actual sequences**: Mostly unchanged or slightly faster (0-25% improvement)
- **Custom sequence-like objects**: Minimal impact since they still need full evaluation

The optimization maintains identical behavior while significantly reducing computational overhead for the most common rejection cases.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 November 12, 2025 20:55
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Nov 12, 2025
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.

1 participant