Previous Page
Next Page

9.4. The pprint Module

The pprint module pretty-prints complicated data structures, with formatting that may be more readable than that supplied by built-in function repr (covered in repr on page 166). To fine-tune the formatting, you can instantiate the PrettyPrinter class supplied by module pprint and apply detailed control, helped by auxiliary functions also supplied by module pprint. Most of the time, however, one of the two main functions exposed by module pprint suffices.

pformat

pformat(obj)

Returns a string representing the pretty-printing of obj.

pprint

pprint(obj,stream=sys.stdout)

Outputs the pretty-printing of obj to file object stream, with a terminating newline.

The following statements are the same:

print pprint.pformat(x)
pprint.pprint(x)

Either of these constructs will be roughly the same as print x in many cases, such as when the string representation of x fits within one line. However, with something like x=range(30), print x displays x in two lines, breaking at an arbitrary point, while using module pprint displays x over 30 lines, one line per item. You can use module pprint when you prefer the module's specific display effects to the ones of normal string representation.



Previous Page
Next Page