diff --git a/tests/test_items.py b/tests/test_items.py index f6377d02..537c2561 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -559,6 +559,14 @@ def test_array_add_line() -> None: ) +def test_array_add_line_comment_does_not_comment_out_closing_bracket() -> None: + array = api.array() + array.add_line("foo", comment="bar") + rendered = array.as_string() + assert rendered == '[\n "foo", # bar\n]' + parse(f"array = {rendered}") + + 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 c950e5d0..d372b104 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -1464,7 +1464,16 @@ 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())}]" + items = list(self._iter_items()) + body = "".join(v.as_string() for v in items) + # A trailing line comment would otherwise swallow the closing ']'. + if ( + items + and isinstance(items[-1], Comment) + and not body.endswith(("\n", "\r")) + ): + body += "\n" + return f"[{body}]" s = "[\n" s += "".join(