Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions tests/test_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,36 @@ def test_key_automatically_sets_proper_string_type_if_not_bare() -> None:
assert key.t == KeyType.Basic


@pytest.mark.parametrize(
"index, replacement",
[
(slice(None), [4, 5, 6]),
(slice(1, 2), [4, 5]),
(slice(1, 1), [4]),
(slice(1, 3), []),
(slice(None, None, 2), [4, 5]),
(slice(None, None, -1), [4, 5, 6]),
],
)
def test_array_slice_assignment_does_not_mutate(
index: slice, replacement: list[int]
) -> None:
content = "a = [\n 1, # first\n 2,\n 3,\n]\n"
doc = parse(content)
a = doc["a"]

with pytest.raises(ValueError, match="slice assignment is not supported"):
a[index] = replacement

assert a == [1, 2, 3]
assert doc.as_string() == content

a[-1] = 4
a.append(5)
assert a == [1, 2, 4, 5]
assert parse(doc.as_string())["a"] == a


def test_array_behaves_like_a_list() -> None:
a = item([1, 2])

Expand Down
4 changes: 2 additions & 2 deletions tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -1584,10 +1584,10 @@ def __getitem__(self, key: int | slice) -> Any: # type: ignore[override]
return list.__getitem__(self, key)

def __setitem__(self, key: int | slice, value: Any) -> None: # type: ignore[override]
it = item(value, _parent=self)
list.__setitem__(self, key, it)
if isinstance(key, slice):
raise ValueError("slice assignment is not supported")
it = item(value, _parent=self)
list.__setitem__(self, key, it)
if key < 0:
key += len(self)
self._value[self._index_map[key]].value = it
Expand Down