Suppress unicode prefix on strings when using pprint

jterrace picture jterrace · Jun 3, 2013 · Viewed 7.2k times · Source

Is there any clean way to supress the unicode character prefix when printing an object using the pprint module?

>>> import pprint
>>> pprint.pprint({u'foo': u'bar', u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'hello': u'world'})
{u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'],
 u'foo': u'bar',
 u'hello': u'world'}

This looks pretty ugly. Is there any way to print the __str__ value of each object, instead of the __repr__?

Answer

Benjamin Toueg picture Benjamin Toueg · Jun 3, 2013

It could be done by overriding the format method of the PrettyPrinter object, and casting any unicode object to string:

import pprint

def my_safe_repr(object, context, maxlevels, level):
    typ = pprint._type(object)
    if typ is unicode:
        object = str(object)
    return pprint._safe_repr(object, context, maxlevels, level)

printer = pprint.PrettyPrinter()
printer.format = my_safe_repr
printer.pprint({u'foo': u'bar', u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'hello': u'world'})

which gives:

{'baz': ['apple', 'orange', 'pear', 'guava', 'banana'],
 'foo': 'bar',
 'hello': 'world'}