Skip to content

Instantly share code, notes, and snippets.

@ydm
Created April 11, 2013 21:20
Show Gist options
  • Save ydm/5367272 to your computer and use it in GitHub Desktop.
Save ydm/5367272 to your computer and use it in GitHub Desktop.
Variant of pprint and pformat functions that do not escape unicode characters.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from StringIO import StringIO
import pprint as pprint
import sys
# Original idea: http://softwaremaniacs.org/forum/python/25696/
class DecoderStream:
def __init__(self, stream):
self._stream = stream
def write(self, s):
s = s.decode('unicode_escape').encode('utf-8')
return self._stream.write(s)
# TODO: Use the custom decoder only if six.PY3 is False
def unipprint(obj, stream=None, **kwargs):
if stream is None:
stream = sys.stdout
pprint.pprint(obj, DecoderStream(stream), **kwargs)
def unipformat(obj, **kwargs):
stream = StringIO()
kwargs['stream'] = stream
unipprint(obj, **kwargs)
return stream.getvalue().decode('utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment