diff --git a/tests/test_items.py b/tests/test_items.py index e331cae..1cdbf6b 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -529,6 +529,16 @@ def test_array_add_line() -> None: ) +def test_array_add_line_single_line_comment_round_trips() -> None: + # A single-line array whose last rendered element is a trailing comment + # (from add_line(..., comment=...)) must keep the closing bracket off the + # comment line, otherwise the output does not round-trip (GH #580). + t = api.array() + t.add_line("foo", comment="bar") + rendered = t.as_string() + assert parse("a = " + rendered)["a"] == ["foo"] + + def test_array_add_line_multiline_comment_is_rejected() -> None: t = api.array() with pytest.raises(ValueError, match="line breaks"): diff --git a/tomlkit/items.py b/tomlkit/items.py index 31369b0..caf23eb 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -1464,7 +1464,14 @@ def multiline(self, multiline: bool) -> Array: def as_string(self) -> str: if not self._multiline or not self._value: - return f"[{''.join(v.as_string() for v in self._iter_items())}]" + rendered = list(self._iter_items()) + inner = "".join(v.as_string() for v in rendered) + if rendered and isinstance(rendered[-1], Comment): + # A trailing comment (e.g. from add_line(comment=...)) carries + # no newline, so keep the closing bracket off the comment line + # to produce parseable output (GH #580). + inner += "\n" + self.trivia.indent + return f"[{inner}]" s = "[\n" s += "".join(