Skip to content

Commit

Permalink
Fix printing unsortable dict (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
gaogaotiantian authored Mar 9, 2022
1 parent 95e6a62 commit b4808f0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/objprint/objprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,14 @@ def _objstr(self, obj, memo, indent_level, cfg):
if isinstance(obj, list) or isinstance(obj, tuple) or isinstance(obj, set):
elems = (f"{self._objstr(val, memo, indent_level + 1, cfg)}" for val in obj)
elif isinstance(obj, dict):
items = obj.items()
try:
items = sorted(items)
except TypeError:
pass
elems = (
f"{self._objstr(key, None, indent_level + 1, cfg)}: {self._objstr(val, memo, indent_level + 1, cfg)}"
for key, val in sorted(obj.items())
for key, val in items
)
else:
# It's an object
Expand Down
8 changes: 8 additions & 0 deletions tests/test_objprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,14 @@ def test_no_color(self):
self.assertNotIn(COLOR.CYAN, output)
self.assertNotIn(COLOR.DEFAULT, output)

def test_unsortable_dict(self):
d = {1: 2, "a": 3}
with io.StringIO() as buf, redirect_stdout(buf):
op(d, color=False)
output = buf.getvalue()
self.assertIn("1", output)
self.assertIn("a", output)

def test_label_only(self):
with io.StringIO() as buf, redirect_stdout(buf):
obj = ObjTest({"Age": 10, "grade": 5})
Expand Down

0 comments on commit b4808f0

Please sign in to comment.