diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index de50a2ce..8afd6816 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -1803,6 +1803,36 @@ def test_update_out_of_order_table_preserves_siblings( assert parse(doc.as_string()).unwrap() == expected +def test_delete_keys_through_the_same_out_of_order_table() -> None: + content = """\ +[tool.a] +x = 1 +[project] +name = "p" +[tool.b] +y = 2 +[other] +[tool.c] +z = 3 +""" + doc = parse(content) + tool = doc["tool"] + del tool["a"] + del tool["b"] + assert ( + doc.as_string() + == """\ +[project] +name = "p" +[other] +[tool.c] +z = 3 +""" + ) + tool["c"] = {"w": 4} + assert doc["tool"] == {"c": {"w": 4}} + + def test_parse_aot_without_ending_newline() -> None: content = '''\ [[products]] diff --git a/tomlkit/container.py b/tomlkit/container.py index 718431a6..cf33d8b5 100644 --- a/tomlkit/container.py +++ b/tomlkit/container.py @@ -1268,7 +1268,11 @@ def _is_table_or_aot(it: Any) -> bool: def _remove_table(self, table: Table) -> None: """Remove table from the parent container""" - self._tables.remove(table) + pos = next(i for i, t in enumerate(self._tables) if t is table) + del self._tables[pos] + # Later tables shift down by one; keep the key -> table index map valid. + for indices in self._tables_map.values(): + indices[:] = [i - 1 if i > pos else i for i in indices if i != pos] for idx, body_item in enumerate(self._container._body): if body_item[1] is table: self._container._remove_at(idx) @@ -1279,7 +1283,7 @@ def __delitem__(self, key: Key | str) -> None: if _key not in self._tables_map: raise NonExistentKey(key) - for i in reversed(self._tables_map[_key]): + for i in reversed(list(self._tables_map[_key])): table = self._tables[i] del table[key] if not table and len(self._tables) > 1: