Skip to content

Commit a963fe1

Browse files
authored
Preserve inline table key order in item() (#546) (#552)
* Preserve inline table key order in item() `item()` sorted dict-valued keys last in the list/tuple branch even under the default ``sort_keys=False``, because the sort key kept ``isinstance(i[1], dict)`` in the tuple unconditionally (unlike the dict branch). For an inline table this silently reordered keys, e.g. ``item([[{"a": {"x": 1}, "b": 2}]])`` produced ``[[{b = 2, a = {x = 1}}]]``. Only apply the dicts-last ordering to arrays of tables (which render as ``[[table]]`` headers, where a dict-valued key would otherwise capture the following keys). Inline tables cannot capture, so their insertion order is now preserved unless sorting is explicitly requested. Closes #546 * Sort inline table keys purely alphabetically with sort_keys=True Inline tables have no capture concern, so there is no reason to force dict-valued keys last when sorting: dicts-last is a capture-avoidance mechanism for [[table]] headers, not a sorting preference. Sort inline table keys purely by key when sort_keys=True. Addresses review feedback on #552. --------- Co-authored-by: uttam12331 <[email protected]>
1 parent 446d6fa commit a963fe1

3 files changed

Lines changed: 37 additions & 4 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
- Fix invalid serialization with a duplicated comma when appending or inserting into a comma-first formatted array. ([#499](https://github.com/python-poetry/tomlkit/pull/499))
3333
- Fix `ParseError` when a sub-table extends the last element of an array of tables after an unrelated table. ([#261](https://github.com/python-poetry/tomlkit/issues/261))
3434
- Fix unparseable serialization when adding a key to a dotted-key table inside an inline table. ([#500](https://github.com/python-poetry/tomlkit/pull/500))
35+
- Fix `item()` reordering the keys of an inline table (dict-valued keys were forced last) under the default `sort_keys=False`. ([#546](https://github.com/python-poetry/tomlkit/issues/546))
3536
- Fix a table replaced by a plain value being serialized inside the preceding table's body when other tables follow; the value now moves before the first table like other root-level values. ([#504](https://github.com/python-poetry/tomlkit/issues/504))
3637
- Fix assigning a table over a dotted key (e.g. `doc["a"] = {...}` where `a` came from `a.b = ...`): the dotted prefix was duplicated onto the new `[a]` header, and the header then swallowed any sibling that follows it on round-trip. The replacement now renders as a plain table and, when needed, moves before the inline entries (values and dotted keys) it would otherwise capture. ([#513](https://github.com/python-poetry/tomlkit/issues/513), [#524](https://github.com/python-poetry/tomlkit/issues/524))
3738
- Restore `dumps()` rendering mapping-like wrappers around a parsed document (e.g. `dotty_dict`'s `Dotty`) through their delegated `as_string`, preserving the original table order and layout instead of re-encoding through a plain dict — a 0.15.0 regression. ([#482](https://github.com/python-poetry/tomlkit/issues/482))

‎tests/test_api.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,29 @@ def test_item_mixed_aray() -> None:
391391
assert dumps({"x": {"y": example}}).strip() == "[x]\ny = " + expected
392392

393393

394+
def test_item_inline_table_preserves_key_order() -> None:
395+
# Inline tables cannot capture following keys, so their key order must be
396+
# preserved under the default sort_keys=False, even when a value is itself
397+
# a dict/table (#546).
398+
assert (
399+
tomlkit.item([[{"a": {"x": 1}, "b": 2}]]).as_string().strip()
400+
== "[[{a = {x = 1}, b = 2}]]"
401+
)
402+
403+
# Arrays of tables still render dict-valued keys last to avoid them
404+
# capturing the following keys.
405+
assert (
406+
tomlkit.item([{"a": {"x": 1}, "b": 2}]).as_string() == "b = 2\n\n[a]\nx = 1\n"
407+
)
408+
409+
# Sorting is purely alphabetical when explicitly requested: inline tables
410+
# have no capture concern, so dict-valued keys are not forced last.
411+
assert (
412+
tomlkit.item([{"b": 2, "a": {"x": 1}}, "s"], _sort_keys=True).as_string()
413+
== '[{a = {x = 1}, b = 2}, "s"]'
414+
)
415+
416+
394417
def test_build_super_table() -> None:
395418
doc = tomlkit.document()
396419
table = tomlkit.table(True)

‎tomlkit/items.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,14 +161,23 @@ def item(value: Any, _parent: Item | None = None, _sort_keys: bool = False) -> I
161161
a = Array([], Trivia())
162162
table_constructor = InlineTable
163163

164+
if table_constructor is Table:
165+
# AoT tables render as ``[[table]]`` headers, so dict-valued keys
166+
# must come last to avoid them capturing the following keys.
167+
def _sort_key(i: tuple[Any, Any]) -> Any:
168+
return (isinstance(i[1], dict), i[0] if _sort_keys else 1)
169+
else:
170+
# Inline tables cannot capture, so there is no need to put
171+
# dict-valued keys last: preserve insertion order, or sort purely
172+
# by key when explicitly requested. See #546.
173+
def _sort_key(i: tuple[Any, Any]) -> Any:
174+
return i[0] if _sort_keys else 1
175+
164176
for v in value:
165177
if isinstance(v, dict):
166178
table = table_constructor(Container(), Trivia(), True)
167179

168-
for k, _v in sorted(
169-
v.items(),
170-
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),
171-
):
180+
for k, _v in sorted(v.items(), key=_sort_key):
172181
i = item(_v, _parent=table, _sort_keys=_sort_keys)
173182
if isinstance(table, InlineTable):
174183
i.trivia.trail = ""

0 commit comments

Comments
 (0)