From f43ea3679dc00d264ad94bb9c42cb7ae3df75cf4 Mon Sep 17 00:00:00 2001 From: velutinous <363301395+velutinous@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:23:31 +0000 Subject: [PATCH] Use a spaced separator when adding to a single-entry inline table A key added after parsing to an inline table with one entry (or none) was written after a bare ",": setting "c" on `a = {b = 1}` gave `a = {b = 1,c = 2}`. Tables with two or more entries already copy the ", " spacing of their explicit separators, but a one-entry table has no separator to copy, and the comma was followed by a space only for tables built in code. The comma is now followed by a space unless the text after it already starts with whitespace, so a padded table such as `{ b = 1 }` still gets exactly one space. A dict appended to an array goes through the same path and is now written as `{name = "John Doe", email = "..."}`. --- CHANGELOG.md | 1 + tests/test_items.py | 28 +++++++++++++++++++++++++++- tomlkit/items.py | 12 +++++++++++- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2e8c49c..ae6c783a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - `item()` and `dumps()` now write the underlying characters of a `str` subclass instead of calling its `__str__` method, so `str`-based `Enum` members and custom string wrappers round-trip again instead of being serialized as e.g. `"Color.RED"` or producing invalid TOML. This was a regression from the single-pass escaping added in 0.15.3. ([#725](https://github.com/python-poetry/tomlkit/issues/725)) - The parser now rejects numbers with non-ASCII digits, such as `1٠` or `10`. Previously `int()` and `float()` converted them, so an invalid document parsed to a wrong value. ([#728](https://github.com/python-poetry/tomlkit/pull/728)) +- Fix a key added to a parsed inline table with a single entry (or none) being written after a bare `,`: setting `c` on `a = {b = 1}` gave `a = {b = 1,c = 2}`. It now gives `a = {b = 1, c = 2}`, as it already did for tables with two or more entries. A dict appended to an array is written the same way. - Fix deleting one of several nested dotted keys inside an inline table writing invalid TOML: deleting `c` from `x = {a.b.c = 1, a.b.d = 2}` gave `x = {a.b = {}, a.b.d = 2}`, which defines `a.b` twice. The emptied part is now removed from the document, as it already was for a single-level dotted key. ([#732](https://github.com/python-poetry/tomlkit/pull/732)) ## [0.15.3] - 2026-11-24 diff --git a/tests/test_items.py b/tests/test_items.py index fee4b68e..8f0a9ba7 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -669,7 +669,7 @@ def test_append_to_multiline_array_with_comment() -> None: def test_append_dict_to_array() -> None: doc = parse("x = []") doc["x"].append({"name": "John Doe", "email": "john@doe.com"}) - expected = 'x = [{name = "John Doe",email = "john@doe.com"}]' + expected = 'x = [{name = "John Doe", email = "john@doe.com"}]' assert doc.as_string() == expected # Make sure the produced string is valid assert parse(doc.as_string()) == doc @@ -1419,6 +1419,32 @@ def test_appending_to_compact_inline_table_uses_spaced_separator() -> None: assert parse(doc.as_string()) == {"a": {"x": 1, "y": 2, "z": 3}} +def test_adding_to_single_entry_inline_table_uses_spaced_separator() -> None: + # A table with a single entry has no separator to copy, so a key added + # after parsing must still get ", " rather than a bare "," ("b = 1,c = 2"). + doc = parse("a = {b = 1}\n") + doc["a"]["c"] = 2 + doc["a"]["d"] = {"e": 1} + + assert doc.as_string() == "a = {b = 1, c = 2, d = {e = 1}}\n" + assert parse(doc.as_string()) == {"a": {"b": 1, "c": 2, "d": {"e": 1}}} + + +def test_adding_to_empty_parsed_inline_table_uses_spaced_separator() -> None: + doc = parse("a = {}\n") + doc["a"]["x"] = 1 + doc["a"]["y"] = 2 + + assert doc.as_string() == "a = {x = 1, y = 2}\n" + + +def test_adding_to_padded_single_entry_inline_table_keeps_one_space() -> None: + doc = parse("a = { b = 1 }\n") + doc["a"]["c"] = 2 + + assert doc.as_string() == "a = { b = 1, c = 2}\n" + + 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 9d6cd607..443248f4 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -2387,13 +2387,23 @@ def as_string(self) -> str: and i < last_item_idx ): buf += "," - if self._new: + if self._new or not self._space_follows(i): buf += " " buf += "}" return buf + def _space_follows(self, i: int) -> bool: + """Whether the text rendered after body element ``i`` starts with + whitespace, so a separator comma placed before it needs no space.""" + body = self._value.body + if i + 1 >= len(body): + return False + k, v = body[i + 1] + following = v.s if k is None and isinstance(v, Whitespace) else v.trivia.indent + return following[:1] in (" ", "\t") + def _render_dotted(self, key: Key, table: Table) -> list[str]: """Render a table materialized from a dotted key as a list of ``prefix.child = value`` strings, recursing into nested dotted