A problem that has frequently come up in my career is I have some kind of data structure (perhaps an s-expression) and I want to print it in a human readable form complete with reasonable indentation choices.
Is there a book or blog entry that describes how to do this elegantly? I am interested in the algorithm more than a specific library.
Pretty-printing (or prettyprinting) is the application of any of various stylistic formatting conventions to text files, such as source code, markup, and similar kinds of content.
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter.
To use pprint, begin by importing the library at the top of your Python file. From here you can either use the . pprint() method or instantiate your own pprint object with PrettyPrinter() .
S-Exps are equivalent to tree structures, if you can pretty-print a tree you can pretty-print an s-exp.
For instance, compare:
(tree
(value 89)
(tree
(value 9)
nil
nil)
(tree
(value 456)
nil
nil))
to:
89
+- 9
+- 456
The algorithm is identical, the only difference is the ammount of surrounding data you want to print out.
This paper describes an algorithm for pretty-printing trees
This one describes a pretty-printer for programming languages
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With