diff --git a/tests/test_items.py b/tests/test_items.py index f5cbbde..465ff7d 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -923,6 +923,14 @@ def test_deleting_inline_table_element_does_not_leave_trailing_separator2() -> N assert table.as_string() == '{ baz = "boom"}' +def test_appending_to_parsed_inline_table_preserves_separator() -> None: + doc = parse("a = { foo = 1, bar = 2 }\n") + doc["a"]["baz"] = 3 + + assert doc.as_string() == "a = { foo = 1, bar = 2, baz = 3}\n" + parse(doc.as_string()) + + def test_booleans_comparison() -> None: boolean = Bool(True, Trivia()) diff --git a/tomlkit/items.py b/tomlkit/items.py index 8670f03..70156e4 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -2037,6 +2037,7 @@ def append(self, key: Key | str | None, _item: Any) -> InlineTable: def as_string(self) -> str: buf = "{" emitted_key = False + needs_separator = False has_explicit_commas = any( k is None and isinstance(v, Whitespace) and "," in v.s for k, v in self._value.body @@ -2073,10 +2074,18 @@ def as_string(self) -> str: elif not has_explicit_commas or "," in v.as_string(): buf = buf.rstrip(",") - buf += v.as_string() + v_string = v.as_string() + buf += v_string + if "," in v_string: + needs_separator = False continue + if has_explicit_commas and needs_separator: + stripped = buf.rstrip() + buf = f"{stripped},{buf[len(stripped) :]}" + needs_separator = False + v_trivia_trail = v.trivia.trail.replace("\n", "") buf += ( f"{v.trivia.indent}" @@ -2087,6 +2096,8 @@ def as_string(self) -> str: f"{v_trivia_trail}" ) emitted_key = True + if has_explicit_commas: + needs_separator = True if ( not has_explicit_commas