Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the default ordering of dicts and add support for sorting keys #103

Merged
merged 1 commit into from
Jul 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 54 additions & 3 deletions tests/test_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from tomlkit import inline_table
from tomlkit import parse
from tomlkit._compat import PY2
from tomlkit._compat import OrderedDict
from tomlkit.exceptions import NonExistentKey
from tomlkit.items import Bool
from tomlkit.items import InlineTable
Expand Down Expand Up @@ -208,8 +209,56 @@ def test_dicts_are_converted_to_tables():
)


def test_dicts_are_converted_to_tables_and_sorted():
t = item({"foo": {"bar": "baz", "abc": 123, "baz": [{"c": 3, "b": 2, "a": 1}]}})
def test_dicts_are_converted_to_tables_and_keep_order():
t = item(
OrderedDict(
[
(
"foo",
OrderedDict(
[
("bar", "baz"),
("abc", 123),
("baz", [OrderedDict([("c", 3), ("b", 2), ("a", 1)])]),
]
),
)
]
)
)

assert (
t.as_string()
== """[foo]
bar = "baz"
abc = 123

[[foo.baz]]
c = 3
b = 2
a = 1
"""
)


def test_dicts_are_converted_to_tables_and_are_sorted_if_requested():
t = item(
OrderedDict(
[
(
"foo",
OrderedDict(
[
("bar", "baz"),
("abc", 123),
("baz", [OrderedDict([("c", 3), ("b", 2), ("a", 1)])]),
]
),
)
]
),
_sort_keys=True,
)

assert (
t.as_string()
Expand All @@ -226,7 +275,9 @@ def test_dicts_are_converted_to_tables_and_sorted():


def test_dicts_with_sub_dicts_are_properly_converted():
t = item({"foo": {"bar": {"string": "baz"}, "int": 34, "float": 3.14}})
t = item(
{"foo": {"bar": {"string": "baz"}, "int": 34, "float": 3.14}}, _sort_keys=True
)

assert (
t.as_string()
Expand Down
6 changes: 6 additions & 0 deletions tomlkit/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ def _name_from_offset(delta):
long = int


if PY36:
OrderedDict = dict
else:
from collections import OrderedDict


def decode(string, encodings=None):
if not PY2 and not isinstance(string, bytes):
return string
Expand Down
4 changes: 2 additions & 2 deletions tomlkit/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ def loads(string): # type: (str) -> _TOMLDocument
return parse(string)


def dumps(data): # type: (_TOMLDocument) -> str
def dumps(data, sort_keys=False): # type: (_TOMLDocument, bool) -> str
"""
Dumps a TOMLDocument into a string.
"""
if not isinstance(data, _TOMLDocument) and isinstance(data, dict):
data = item(data)
data = item(data, _sort_keys=sort_keys)

return data.as_string()

Expand Down
16 changes: 10 additions & 6 deletions tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from functools import lru_cache


def item(value, _parent=None):
def item(value, _parent=None, _sort_keys=False):
from .container import Container

if isinstance(value, Item):
Expand All @@ -42,8 +42,11 @@ def item(value, _parent=None):
return Float(value, Trivia(), str(value))
elif isinstance(value, dict):
val = Table(Container(), Trivia(), False)
for k, v in sorted(value.items(), key=lambda i: (isinstance(i[1], dict), i[0])):
val[k] = item(v, _parent=val)
for k, v in sorted(
value.items(),
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),
):
val[k] = item(v, _parent=val, _sort_keys=_sort_keys)

return val
elif isinstance(value, list):
Expand All @@ -57,13 +60,14 @@ def item(value, _parent=None):
table = Table(Container(), Trivia(), True)

for k, _v in sorted(
v.items(), key=lambda i: (isinstance(i[1], dict), i[0])
v.items(),
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),
):
i = item(_v)
i = item(_v, _sort_keys=_sort_keys)
if isinstance(table, InlineTable):
i.trivia.trail = ""

table[k] = item(i)
table[k] = item(i, _sort_keys=_sort_keys)

v = table

Expand Down