Skip to content

Commit 2c87eaf

Browse files
Honor sort_keys for parsed TOML documents (#471)
Co-authored-by: ShipItAndPray <[email protected]>
1 parent 8e32f9c commit 2c87eaf

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

‎tests/test_api.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,12 @@ def test_mapping_types_can_be_dumped() -> None:
166166
assert dumps(x) == 'foo = "bar"\n'
167167

168168

169+
def test_parsed_document_can_be_dumped_with_sorted_keys() -> None:
170+
doc = loads('zzz = 1\naaa = "foo"')
171+
172+
assert dumps(doc, sort_keys=True) == 'aaa = "foo"\nzzz = 1\n'
173+
174+
169175
def test_dumps_weird_object() -> None:
170176
with pytest.raises(TypeError):
171177
dumps(object()) # type: ignore[arg-type]

‎tomlkit/api.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,12 @@ def dumps(data: Mapping[str, Any], sort_keys: bool = False) -> str:
5858
Dumps a TOMLDocument into a string.
5959
"""
6060
if isinstance(data, (Table, InlineTable, Container)):
61-
return data.as_string()
61+
if not sort_keys:
62+
return data.as_string()
6263

63-
table: Table = item(dict(data), _sort_keys=sort_keys)
64+
return item(data, _sort_keys=True).as_string()
65+
66+
table = item(dict(data), _sort_keys=sort_keys)
6467
return table.as_string()
6568

6669

0 commit comments

Comments
 (0)