Repository navigation
[mypyc] Fix crash when iterating over bytearray - #22432
Merged
Merged
Conversation
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.
13 of 14 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Iterating over a
bytearraycrashed mypyc with an internal error (ValueError: bytearray is not a valid sequence). This affectedforloops and comprehensions:bytearrayis a sequence primitive type, so the index-based loop was used, butget_sequence_type_from_type()didn't know its item type.Index-based iteration isn't a good fit for
bytearray:__len__and__getitem__, which iteration must not use;So
bytearraynow 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
bytesto beintinstead ofbytes. This was harmless, since theintitem was only boxed and then unboxed again. Removing the box/unbox makes iterating overbytesabout 2.7x faster forforloops and 2x faster for list comprehensions.Tests cover
forloops, comprehensions,enumerate/zip, generators, modifying the bytearray while iterating, and subclasses that override__len__/__getitem__or__iter__.