Pretty-printing Python interactive output?

Skip Montanaro skip at mojam.com
Wed Sep 8 15:53:59 EDT 1999


    >> Is there an easy way or device by which `pprint.pprint' could be
    >> called automatically on the expression returned by the interactive
    >> interpreter?

I thought the following placed in your $PYTHONSTARTUP file would have done
the trick, but I guess the interpreter loop doesn't use __builtin__.repr or
__builtin__.str to format objects for printing.  Looks like PyObject_Print
gets called to emit the object's representation.  Not sure what bits to
twiddle to get it to use repr()/str().

    try:
        import pprint, __builtin__
        class Writer:
            def __init__(self):
                self.pp = pprint.PrettyPrinter()

            def repr(self, obj):
                return self.pp.pformat(obj)

            str = repr

        __builtin__.repr = Writer().repr
        __builtin__.str = Writer().str

    except ImportError:
        print "failed to define alternate repr()!"

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/~skip/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list