From cceed88b631d890c5210b9b03dd5af2c4956bc29 Mon Sep 17 00:00:00 2001 From: gottostartsomewhere Date: Wed, 8 Jul 2026 18:04:38 +0530 Subject: [PATCH] Fix list slicing with a zero stop or negative indices 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. --- mollie/api/objects/list.py | 8 +++++--- tests/test_list.py | 6 ++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/mollie/api/objects/list.py b/mollie/api/objects/list.py index b8fd3f46..07822e96 100644 --- a/mollie/api/objects/list.py +++ b/mollie/api/objects/list.py @@ -42,9 +42,11 @@ def __getitem__(self, key): return self.object_type(item, self.client) if isinstance(key, slice): - _start = key.start or 0 - _stop = key.stop or self["count"] - _step = key.step or 1 + # slice.indices() correctly resolves None, negative and out-of-range + # bounds. The previous ``key.stop or self["count"]`` treated a stop + # of 0 as "unset", so e.g. ``obj_list[:0]`` returned the whole list + # instead of an empty one (and negative indices were mishandled). + _start, _stop, _step = key.indices(len(self)) sliced_data = [self["_embedded"][object_name][x] for x in range(_start, _stop, _step)] # Now we mock a result based on the sliced data sliced_result = { diff --git a/tests/test_list.py b/tests/test_list.py index 29db795a..5e07bf5d 100644 --- a/tests/test_list.py +++ b/tests/test_list.py @@ -158,3 +158,9 @@ def test_list_supports_slice_sequences(client, response): slice_step_only = methods[::3] assert_list_object(slice_step_only, Method, 4), "Slicing with only a step value should be possible" assert [x.id for x in slice_step_only] == ["ideal", "bancontact", "kbc", "giftcard"] + + slice_empty = methods[:0] + assert [x.id for x in slice_empty] == [], "A slice with a stop of 0 should be empty" + + slice_negative = methods[-2:] + assert [x.id for x in slice_negative] == ["inghomepay", "giftcard"], "Negative slicing should be possible"