Skip to content

Fix doubled comma when inserting into a comma-first array#499

Merged
frostming merged 1 commit into
python-poetry:masterfrom
gaoflow:fix/494-comma-first-array-insert
Jun 10, 2026
Merged

Fix doubled comma when inserting into a comma-first array#499
frostming merged 1 commit into
python-poetry:masterfrom
gaoflow:fix/494-comma-first-array-insert

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Fixes #494.

In a comma-first formatted array the comma that separates an item from the previous one lives in that item's indent whitespace (the parser folds \n , into the next group's indent when a comment ends the previous group). Array.insert() copies such an indent onto the new item, but then also adds a trailing comma to the previous item — and for middle inserts gives the new item a trailing comma too — so the output contains double separators and no longer parses:

doc = tomlkit.parse("a = [\n      1 # one\n     ,2\n    ]\n")
doc["a"].append(99)
tomlkit.parse(tomlkit.dumps(doc))  # UnexpectedCharError: ',' — dumped "2,\n     ,99"

The fix skips both extra commas when the indent copied onto the new item already carries one: the embedded comma is the separator. Output is style-preserving (,2,99) and round-trips. Same structure as the __delitem__ comma_in_indent handling from #486, which insert() never got.

Regression tests cover append, middle insert (both previously produced unparseable output), and front insert (comma-less indent, unchanged behavior).

In a comma-first formatted array the separator of an item after a
comment lives in that item's indent whitespace. Array.insert() copied
such an indent onto the new item while also adding a trailing comma to
the previous item (and, for middle inserts, to the new item), producing
a double separator that no longer parses, e.g. `2,` followed by `,99`.

Skip the extra commas when the copied indent already carries one.
@gaoflow gaoflow force-pushed the fix/494-comma-first-array-insert branch from 2aab1e4 to 3313f24 Compare June 9, 2026 18:44
@frostming frostming merged commit f8ce14b into python-poetry:master Jun 10, 2026
25 checks passed
@frostming

Copy link
Copy Markdown
Contributor

Thanks

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.

tomlkit inserts an invalid comma when appending to unusually formatted array

2 participants