diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d04d5a..c14e764 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [unreleased] +### Fixed + +- Fix invalid serialization with a duplicated comma when removing a non-edge element from a parsed inline table. ([#486](https://github.com/python-poetry/tomlkit/pull/486)) + ## [0.15.0] - 2026-05-10 ### Changed diff --git a/tests/test_items.py b/tests/test_items.py index 465ff7d..b8bd95c 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -931,6 +931,19 @@ def test_appending_to_parsed_inline_table_preserves_separator() -> None: parse(doc.as_string()) +def test_deleting_inline_table_middle_element_does_not_leave_double_separator() -> None: + doc = parse("a = {foo = 1, bar = 2, baz = 3}\n") + del doc["a"]["bar"] + + # The dangling separator left by the removed key must not produce an + # invalid ``, ,`` sequence; the result must round-trip. + rendered = doc.as_string() + assert ", ," not in rendered + assert ",," not in rendered + assert parse(rendered) == {"a": {"foo": 1, "baz": 3}} + assert parse(rendered).as_string() == rendered + + def test_booleans_comparison() -> None: boolean = Bool(True, Trivia()) diff --git a/tomlkit/items.py b/tomlkit/items.py index 70156e4..69fb762 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -2050,6 +2050,7 @@ def as_string(self) -> str: ), None, ) + pending_separator = False for i, (k, v) in enumerate(self._value.body): if k is None: if isinstance(v, Whitespace) and "," in v.s: @@ -2068,6 +2069,15 @@ def as_string(self) -> str: buf += v.as_string().replace(",", "", 1) continue + if pending_separator: + # A previous key was removed, leaving this comma as a + # duplicate of an already emitted separator. Drop it to + # avoid producing an invalid ``, ,`` sequence. + buf += v.as_string().replace(",", "", 1) + continue + + pending_separator = True + if i == len(self._value.body) - 1: if self._new: buf = buf.rstrip(", ") @@ -2096,6 +2106,7 @@ def as_string(self) -> str: f"{v_trivia_trail}" ) emitted_key = True + pending_separator = False if has_explicit_commas: needs_separator = True