Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a custom pretty printer

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.

like image 339
Setjmp Avatar asked Apr 29 '09 13:04

Setjmp


People also ask

What is pretty format?

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.

Which module is required in pretty printing?

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.

How do I turn on pretty printing in Python?

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() .


1 Answers

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

like image 179
dsm Avatar answered Nov 09 '22 23:11

dsm