I like the pprint module in Python. I use it a lot for testing and debugging. I frequently use the width option to make sure the output fits nicely within my terminal window.
It has worked fine until they added the new ordered dictionary type in Python 2.7 (another cool feature I really like). If I try to pretty-print an ordered dictionary, it doesn't show nicely. Instead of having each key-value pair on its own line, the whole thing shows up on one long line, which wraps many times and is hard to read.
Does anyone here have a way to make it print nicely, like the old unordered dictionaries? I could probably figure something out, possibly using the PrettyPrinter.format method, if I spend enough time, but I am wondering if anyone here already knows of a solution.
UPDATE: I filed a bug report for this. You can see it at http://bugs.python.org/issue10592.
You could redefine
pprint()
and intercept calls forOrderedDict
's. Here's a simple illustration. As written, theOrderedDict
override code ignores any optionalstream
,indent
,width
, ordepth
keywords that may have been passed, but could be enhanced to implement them. Unfortunately this technique doesn't handle them inside another container, such as alist
ofOrderDict
'sI've tested this unholy monkey-patch based hack on python3.5 and it works:
You make
pprint
use the usual dict based summary and also disable sorting for the duration of the call so that no keys are actually sorted for printing.