Fix item() reordering dict keys when sort_keys is False#547
Fix item() reordering dict keys when sort_keys is False#547jichaowang02-lang wants to merge 1 commit into
Conversation
In the list-of-dicts branch of item(), the sort-key lambda had a
misplaced closing parenthesis:
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1)
Only `i[0]` was guarded by `if _sort_keys`, so the
`isinstance(i[1], dict)` term stayed active even with the default
sort_keys=False, forcing dict-valued keys to sort after scalar keys and
silently reordering the user's keys. The sibling top-level dict branch
already has the correct form (whole tuple guarded):
key=lambda i: (isinstance(i[1], dict), i[0]) if _sort_keys else 1
The reorder is masked for regular tables (sub-tables are relocated to the
end on render anyway) but is directly visible for inline tables, which
are not relocated. Move the parenthesis to match the sibling branch.
Fixes python-poetry#546.
|
The point of dictionaries-last is surely to avoid accidental captures - If this is unnecessary when not sorting keys, then it also is unnecessary when sorting keys. On the other hand if it is needed here - then it is needed unconditionally. |
|
You're right, thanks — I had this backwards. The dictionaries-last ordering is doing capture-avoidance: a scalar key has to render before a The only thing #546 is really about is cosmetic key order inside inline tables (which can't capture), and that's not worth trading capture-safety for. Closing this — sorry for the noise. |
Problem
Resolves #546.
In the list-of-dicts branch of
item(), the sort-key lambda has a misplaced closing parenthesis:Only
i[0]is guarded byif _sort_keys, so theisinstance(i[1], dict)term stays active even with the defaultsort_keys=False, forcing dict-valued keys to sort after scalar keys — silently reordering the user's keys. The sibling top-level dict branch already has the correct form (the whole tuple guarded):The reorder is masked for regular tables (sub-tables are relocated to the end on render anyway) but is directly visible for inline tables, which are not relocated:
Fix
Move the parenthesis so the whole tuple is guarded by
if _sort_keys, matching the sibling branch a few lines above.Tests
Added
test_item_list_of_dicts_preserves_key_order. Full suite passes (pytest tests/→ 1036 passed). CHANGELOG updated.