Skip to content

Keep single-line array bracket off a trailing comment line - #581

Open
youdie006 wants to merge 1 commit into
python-poetry:masterfrom
youdie006:fix/array-comment-closing-bracket
Open

Keep single-line array bracket off a trailing comment line#581
youdie006 wants to merge 1 commit into
python-poetry:masterfrom
youdie006:fix/array-comment-closing-bracket

Conversation

@youdie006

Copy link
Copy Markdown

Summary

tomlkit.array().add_line("foo", comment="bar").as_string() produced [\n "foo", # bar] — the closing ] landed on the comment line, so the output failed to round-trip (tomlkit.loads(...) raised UnexpectedCharError). Fixes #580.

Array.as_string()'s single-line branch concatenated ] directly after the joined items. A trailing comment (from add_line(..., comment=...)) carries no newline, so the bracket was swallowed by the comment. This moves the bracket onto its own line when the last rendered element is a Comment; genuine single-line arrays ([1, 2, 3]) and multi-line arrays are byte-for-byte unchanged (the existing test_array_add_line assertion still passes).

Note: the issue suggested making add_line promote single-line arrays to multiline, but that reformats add_line(1, 2, 3) onto separate lines and breaks test_array_add_line, so the fix belongs in as_string, not add_line.

Added a regression test (test_array_add_line_single_line_comment_round_trips), verified red before the fix (UnexpectedCharError) and green after. pytest tests/test_items.py (87 passed) and ruff format --check pass locally.

Agent Drafting Metadata

  • Agent: Claude Code
  • Model: Claude (Opus)
  • Notes: AI-assisted. The fix, the regression test, and this description were reviewed and verified locally by me (red-green cycle plus the full tests/test_items.py).

Array.as_string() concatenated the closing bracket directly after the
joined items. When the last rendered element is a trailing comment
(e.g. from add_line(value, comment=...)), the comment carries no
newline, so the ']' landed on the comment line and the output no
longer parsed.

Move the bracket to its own line when the last element is a Comment.
Genuine single-line arrays and multi-line arrays are unaffected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Calling .add_line(…, comment=…) on a single-line array causes invalid serialization

1 participant