Fix list slicing with a zero stop or negative indices#394
Open
gottostartsomewhere wants to merge 1 commit into
Open
Fix list slicing with a zero stop or negative indices#394gottostartsomewhere wants to merge 1 commit into
gottostartsomewhere wants to merge 1 commit into
Conversation
ListBase.__getitem__ resolved slice bounds with `key.stop or self["count"]`, which treats a stop of 0 as unset. As a result obj_list[:0] returned the whole list instead of an empty one, and negative indices were mishandled. Use slice.indices(len(self)), which correctly normalises None, negative and out-of-range bounds. Extend the slice test with zero-stop and negative cases.
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.
Problem
ListBase.__getitem__resolves slice bounds like this:Because
0is falsy,key.stop or self["count"]treats a stop of 0 as "unset". So a slice such asobj_list[:0](conventionally empty) returns the entire list. Negative indices are also mishandled (e.g.obj_list[-2:]produces a wrong, over-long result), since raw negative bounds are passed straight torange().Fix
Use
slice.indices(len(self)), the standard way to normalise slice bounds — it correctly handlesNone, negative, and out-of-range start/stop/step. All previously-passing slices are unchanged.Tests
Extended
test_list_supports_slice_sequenceswith a zero-stop case (methods[:0]→ empty) and a negative case (methods[-2:]→ last two). Both fail onmainand pass with this change; the existing slice assertions continue to pass.