Skip to content

Commit

Permalink
Merge pull request #10767 from jdemeyer/pprint_sorted
Browse files Browse the repository at this point in the history
Sort on string representation if sorting fails
  • Loading branch information
Carreau committed Aug 31, 2017
2 parents 4c81324 + 813a6dc commit ca86b79
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions IPython/lib/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,21 @@ def __init__(self, *args, **kwargs):
"Please use io.StringIO instead."),
DeprecationWarning, stacklevel=2)

def _sorted_for_pprint(items):
"""
Sort the given items for pretty printing. Since some predictable
sorting is better than no sorting at all, we sort on the string
representation if normal sorting fails.
"""
items = list(items)
try:
return sorted(items)
except Exception:
try:
return sorted(items, key=str)
except Exception:
return items

def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
"""
Pretty print the object's representation.
Expand Down Expand Up @@ -568,13 +583,10 @@ def inner(obj, p, cycle):
step = len(start)
p.begin_group(step, start)
# Like dictionary keys, we will try to sort the items if there aren't too many
items = obj
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
try:
items = sorted(obj)
except Exception:
# Sometimes the items don't sort.
pass
items = _sorted_for_pprint(obj)
else:
items = obj
for idx, x in p._enumerate(items):
if idx:
p.text(',')
Expand Down Expand Up @@ -602,11 +614,7 @@ def inner(obj, p, cycle):
keys = obj.keys()
# if dict isn't large enough to be truncated, sort keys before displaying
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
try:
keys = sorted(keys)
except Exception:
# Sometimes the keys don't sort.
pass
keys = _sorted_for_pprint(keys)
for idx, key in p._enumerate(keys):
if idx:
p.text(',')
Expand Down

0 comments on commit ca86b79

Please sign in to comment.