diff --git a/tests/test_items.py b/tests/test_items.py index e331caeb..f1443d57 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -357,6 +357,26 @@ def test_array_behaves_like_a_list() -> None: ) +def test_array_slice_deletion_keeps_render_in_sync() -> None: + # Regression: deleting a slice must keep as_string() consistent with the + # list contents. Slices with stop == 0 or negative bounds previously + # corrupted the rendered array (e.g. `del a[:0]` wiped every element). + a = item([1, 2, 3]) + del a[:0] # deletes nothing + assert a == [1, 2, 3] + assert a.as_string() == "[1, 2, 3]" + + a = item([1, 2, 3]) + del a[-1:] + assert a == [1, 2] + assert a.as_string() == "[1, 2]" + + a = item([1, 2, 3]) + del a[:-1] + assert a == [3] + assert a.as_string() == "[3]" + + def test_array_multiline() -> None: t = item([1, 2, 3, 4, 5, 6, 7, 8]) t.multiline(True) diff --git a/tomlkit/items.py b/tomlkit/items.py index 31369b03..e3d6a2f7 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -1657,9 +1657,7 @@ def __delitem__(self, key: int | slice) -> None: # type: ignore[override] list.__delitem__(self, key) if isinstance(key, slice): - indices_to_remove = list( - range(key.start or 0, key.stop or length, key.step or 1) - ) + indices_to_remove = list(range(*key.indices(length))) else: indices_to_remove = [length + key if key < 0 else key] for i in sorted(indices_to_remove, reverse=True):