Skip to content

Fix list slicing with a zero stop or negative indices#394

Open
gottostartsomewhere wants to merge 1 commit into
mollie:mainfrom
gottostartsomewhere:fix/list-slice-zero-stop
Open

Fix list slicing with a zero stop or negative indices#394
gottostartsomewhere wants to merge 1 commit into
mollie:mainfrom
gottostartsomewhere:fix/list-slice-zero-stop

Conversation

@gottostartsomewhere

Copy link
Copy Markdown

Problem

ListBase.__getitem__ resolves slice bounds like this:

_start = key.start or 0
_stop = key.stop or self["count"]
_step = key.step or 1

Because 0 is falsy, key.stop or self["count"] treats a stop of 0 as "unset". So a slice such as obj_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 to range().

Fix

Use slice.indices(len(self)), the standard way to normalise slice bounds — it correctly handles None, negative, and out-of-range start/stop/step. All previously-passing slices are unchanged.

Tests

Extended test_list_supports_slice_sequences with a zero-stop case (methods[:0] → empty) and a negative case (methods[-2:] → last two). Both fail on main and pass with this change; the existing slice assertions continue to pass.

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

1 participant