home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Previous Section Next Section

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 (see Chapter 8). 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 Section Next Section