item() reorders keys (dict-valued before scalar) even with the default sort_keys=False

Open Beginner friendly
#546 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
72/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Quiet
Tech stack
python
Domain
tooling

Research direction

Start at the items.item() entry point and run the reproduction from the issue with tomlkit 0.15.0 or the referenced master revision. Inspect the list-of-dicts sorting branch and verify that the default sort_keys=False preserves the input order, with the [a] table emitted before b = 2.

Written by the indexing model from the issue text.

Description

Summary

When tomlkit.items.item() builds a value from a Python list of dicts, its sort key has a misplaced parenthesis:
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1). The if _sort_keys else 1 guards only i[0], so the isinstance(i[1], dict) term stays active — dict-valued keys are forced after scalar-valued keys even when sort_keys=False. The sibling top-level branch guards the whole tuple correctly: (isinstance(i[1], dict), i[0]) if _sort_keys else 1.

Reproduction
from tomlkit.items import item
print(item([{'a': {'x': 1}, 'b': 2}]).as_string())
# b = 2
#
# [a]
# x = 1

Input key order is a, b, but b is emitted before the [a] table.

Expected

With the default sort_keys=False, key order is preserved: the [a] table, then b = 2.

Actual

b = 2 is emitted before [a] — keys silently reordered.

Fix sketch

Guard the whole sort tuple with _sort_keys, matching the top-level dict branch.

Environment

tomlkit 0.15.0 (master @ 43668dd), Python 3.12.

Dominant language
Python
Stars
850
Forks
163
Avg merge
13m
Merged PRs (30d)
2

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-poetry/tomlkit

All issues in python-poetry/tomlkit

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.