diff --git a/CHANGELOG.md b/CHANGELOG.md index 3737b80e..edea7022 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Change Log +## [Unreleased] + +### Fixed + +- Fix appending a key to a parsed inline table that uses `", "` separators emitting a bare `","` for the new entry, leaving the table inconsistently spaced (e.g. `{x = 1, y = 2,z = 3}`). ([#595](https://github.com/python-poetry/tomlkit/pull/595)) + ## [0.15.1] - 2026-07-17 ### Changed diff --git a/tests/test_items.py b/tests/test_items.py index e331caeb..cfbe2e1a 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -979,6 +979,17 @@ def test_appending_to_parsed_inline_table_preserves_separator() -> None: parse(doc.as_string()) +def test_appending_to_compact_inline_table_uses_spaced_separator() -> None: + # A compact inline table separates its existing entries with ", " (comma + + # space). A key appended after parsing must use the same spacing, instead of + # a bare "," that leaves the table inconsistently spaced ("y = 2,z = 3"). + doc = parse("a = {x = 1, y = 2}\n") + doc["a"]["z"] = 3 + + assert doc.as_string() == "a = {x = 1, y = 2, z = 3}\n" + assert parse(doc.as_string()) == {"a": {"x": 1, "y": 2, "z": 3}} + + def test_append_key_after_inline_table_trailing_comment() -> None: doc = parse("tbl = {\n p = { k = 1 },\n q = { k = 2 } # comment\n}\n") doc["tbl"]["added"] = 3 diff --git a/tomlkit/items.py b/tomlkit/items.py index 31369b03..79b3bdb2 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -2117,7 +2117,15 @@ def as_string(self) -> str: # Insert the deferred separator right after the previous value, # not after any trailing comment/whitespace -- otherwise the # comma is swallowed by a trailing comment (see #512). - buf = f"{buf[:last_value_end]},{buf[last_value_end:]}" + # Match the conventional ", " spacing used by the explicit + # separators already in the table. Only add the space when the + # text that will follow the comma (the previous value's trailing + # trivia plus the new key's own indent) does not already start + # with one, so a padded table like ``{ a = 1 }`` -- which + # contributes the space itself -- does not end up double-spaced. + following = buf[last_value_end:] + v.trivia.indent + separator = "," if following.startswith(" ") else ", " + buf = f"{buf[:last_value_end]}{separator}{buf[last_value_end:]}" needs_separator = False v_trivia_trail = v.trivia.trail.replace("\n", "")