Skip to content

[mypyc] Fix crash when iterating over bytearray - #22432

Merged
JukkaL merged 2 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-bytearray-iter
Nov 11, 2026
Merged

JukkaL merged 2 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-bytearray-iter

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

Iterating over a bytearray crashed mypyc with an internal error (ValueError: bytearray is not a valid sequence). This affected for loops and comprehensions:

def f(b: bytearray) -> int:
    t = 0
    for c in b:  # internal mypyc error
        t += c
    return t

bytearray is a sequence primitive type, so the index-based loop was used, but get_sequence_type_from_type() didn't know its item type.

Index-based iteration isn't a good fit for bytearray:

  • there is no fast item access primitive for it;
  • a subclass may override __len__ and __getitem__, which iteration must not use;
  • its length can change while iterating, which list comprehensions with a preallocated length don't support.

So bytearray now uses the iterator protocol, like CPython does. Iterating a 100 KB bytearray is about 5.6x faster this way than through the generic __getitem__.

Also fix the item type of bytes to be int instead of bytes. This was harmless, since the int item was only boxed and then unboxed again. Removing the box/unbox makes iterating over bytes about 2.7x faster for for loops and 2x faster for list comprehensions.

Tests cover for loops, comprehensions, enumerate/zip, generators, modifying the bytearray while iterating, and subclasses that override __len__/__getitem__ or __iter__.

Iterating over a bytearray in a for loop or a comprehension crashed with
an internal error, since the item type of bytearray wasn't known. Use the
iterator protocol for bytearray, like CPython. This is faster than the
generic __getitem__, ignores __len__ and __getitem__ overrides in
subclasses, and supports changing the length while iterating.

Also use int as the item type of bytes instead of bytes, which avoids
boxing and unboxing each item.
@Jahongir-Qurbonov Jahongir-Qurbonov mentioned this pull request Nov 10, 2026
13 of 14 tasks

@JukkaL JukkaL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, looks good!

@JukkaL
JukkaL merged commit ec03448 into python:master Nov 11, 2026
18 checks passed
@Jahongir-Qurbonov
Jahongir-Qurbonov deleted the mypyc-bytearray-iter branch November 14, 2026 22:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants