Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress unicode prefix on strings when using pprint

Tags:

python

pprint

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__?

like image 423
jterrace Avatar asked Jun 02 '13 23:06

jterrace


1 Answers

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'}
like image 105
Benjamin Toueg Avatar answered Sep 18 '22 00:09

Benjamin Toueg