forked from M-Labs/artiq
1
0
Fork 0

pyon: sort string dicts by key when pretty-printing. Closes #1010

This commit is contained in:
Sebastien Bourdeauducq 2018-07-15 17:38:09 +08:00
parent b27fa8964b
commit 123e7bc054
1 changed files with 8 additions and 2 deletions

View File

@ -17,6 +17,7 @@ function call syntax to express special data types.
""" """
from operator import itemgetter
import base64 import base64
from fractions import Fraction from fractions import Fraction
from collections import OrderedDict from collections import OrderedDict
@ -113,15 +114,20 @@ class _Encoder:
return r return r
def encode_dict(self, x): def encode_dict(self, x):
if self.pretty and all(k.__class__ == str for k in x.keys()):
items = lambda: sorted(x.items(), key=itemgetter(0))
else:
items = x.items
r = "{" r = "{"
if not self.pretty or len(x) < 2: if not self.pretty or len(x) < 2:
r += ", ".join([self.encode(k) + ": " + self.encode(v) r += ", ".join([self.encode(k) + ": " + self.encode(v)
for k, v in x.items()]) for k, v in items()])
else: else:
self.indent_level += 1 self.indent_level += 1
r += "\n" r += "\n"
first = True first = True
for k, v in x.items(): for k, v in items():
if not first: if not first:
r += ",\n" r += ",\n"
first = False first = False