From 10bf34dbd1edb561c4e8586c630b8d47c4857a1b Mon Sep 17 00:00:00 2001 From: ShipItAndPray Date: Sun, 26 Apr 2026 21:33:44 -0500 Subject: [PATCH] Honor sort_keys for parsed TOML documents --- tests/test_api.py | 6 ++++++ tomlkit/api.py | 7 +++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/test_api.py b/tests/test_api.py index eb27229..c943d06 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -166,6 +166,12 @@ def test_mapping_types_can_be_dumped() -> None: assert dumps(x) == 'foo = "bar"\n' +def test_parsed_document_can_be_dumped_with_sorted_keys() -> None: + doc = loads('zzz = 1\naaa = "foo"') + + assert dumps(doc, sort_keys=True) == 'aaa = "foo"\nzzz = 1\n' + + def test_dumps_weird_object() -> None: with pytest.raises(TypeError): dumps(object()) # type: ignore[arg-type] diff --git a/tomlkit/api.py b/tomlkit/api.py index 7455a1c..1ecf84f 100644 --- a/tomlkit/api.py +++ b/tomlkit/api.py @@ -58,9 +58,12 @@ def dumps(data: Mapping[str, Any], sort_keys: bool = False) -> str: Dumps a TOMLDocument into a string. """ if isinstance(data, (Table, InlineTable, Container)): - return data.as_string() + if not sort_keys: + return data.as_string() - table: Table = item(dict(data), _sort_keys=sort_keys) + return item(data, _sort_keys=True).as_string() + + table = item(dict(data), _sort_keys=sort_keys) return table.as_string()