21

Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.

Is there something that will take any python object and display it in a more rational manner. e.g.

[0, 1,
    [a, b, c],
    2, 3, 4]

instead of:

[0, 1, [a, b, c], 2, 3, 4]

I know that's not a very good example, but I think you get the idea.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299

4 Answers4

30
from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)

Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
11

Somtimes YAML can be good for this.

import yaml
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
print yaml.dump(a)

Produces:

- 0
- 1
- [a, b, c]
- 2
- 3
- 4
rjmunro
  • 27,203
  • 20
  • 110
  • 132
9

In addition to pprint.pprint, pprint.pformat is really useful for making readable __repr__s. My complex __repr__s usually look like so:

def __repr__(self):
    from pprint import pformat

    return "<ClassName %s>" % pformat({"attrs":self.attrs,
                                       "that_i":self.that_i,
                                       "care_about":self.care_about})
AdamKG
  • 13,678
  • 3
  • 38
  • 46
  • pprint(x) is just "print pformat(x)", so you can have access to the what pprint prints out as a string. very helpful sometimes – Amandasaurus Jan 20 '14 at 11:40
3

Another good option is to use IPython, which is an interactive environment with a lot of extra features, including automatic pretty printing, tab-completion of methods, easy shell access, and a lot more. It's also very easy to install.

IPython tutorial

Gregg Lind
  • 20,690
  • 15
  • 67
  • 81
  • 2
    For the record, I believe IPython uses pprint to print things, so if you want to print things like IPython in your own program, you want pprint. – Ryan C. Thompson Nov 05 '09 at 01:57
  • Well, can also import an ipython shell into your program. I point out ipython because it has many many other useful features besides pretty-printing. – Gregg Lind Nov 05 '09 at 14:27