Skip to content

Commit

Permalink
fix behavior of setitem
Browse files Browse the repository at this point in the history
Signed-off-by: Frost Ming <[email protected]>
  • Loading branch information
frostming committed Aug 14, 2024
1 parent b9a7660 commit cc5e1f8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
40 changes: 40 additions & 0 deletions tests/test_toml_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -1147,3 +1147,43 @@ def test_delete_out_of_order_table_key():
"""
)


def test_overwrite_out_of_order_table_key():
content = """\
[foo]
name = "foo"
[bar.a.b]
name = "bar-a-b"
[foo.a]
name = "foo-a"
[bar.a]
name = "bar-a"
[baz]
name = "baz"
[bar.a.c]
name = "bar-a-c"
"""
doc = parse(content)
doc["bar"]["a"] = {"name": "bar-a-updated"}
assert (
doc.as_string()
== """\
[foo]
name = "foo"
[bar.a]
name = "bar-a-updated"
[foo.a]
name = "foo-a"
[baz]
name = "baz"
"""
)
8 changes: 6 additions & 2 deletions tomlkit/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -835,8 +835,12 @@ def __getitem__(self, key: Key | str) -> Any:

def __setitem__(self, key: Key | str, item: Any) -> None:
if key in self._tables_map:
table = self._tables[self._tables_map[key][-1]]
table[key] = item
# Overwrite the first table and remove others
indices = self._tables_map[key]
while len(indices) > 1:
table = self._tables[indices.pop()]
self._remove_table(table)
self._tables[indices[0]][key] = item
elif self._tables:
table = self._tables[0]
table[key] = item
Expand Down

0 comments on commit cc5e1f8

Please sign in to comment.