diff -r 97522b189c79 Lib/pprint.py --- a/Lib/pprint.py Mon Apr 29 10:23:31 2013 -0400 +++ b/Lib/pprint.py Mon Apr 29 21:09:26 2013 +0300 @@ -34,6 +34,7 @@ """ +import base64 as _base64 import re import sys as _sys from collections import OrderedDict as _OrderedDict @@ -101,6 +102,9 @@ "Helper function for comparing 2-tuples" return _safe_key(t[0]), _safe_key(t[1]) +def _chunks(data, size): + return (data[i: i + size] for i in range(0, len(data), size)) + class PrettyPrinter: def __init__(self, indent=1, width=80, depth=None, stream=None): """Handle pretty printing operations onto a stream using a set of @@ -271,6 +275,25 @@ write('\n' + ' '*indent) write(rep) return + + if (issubclass(typ, bytes) and len(object) > 0 and r is bytes.__repr__ and + re.search(b'[^\t\n\r -~]', object)): + write('base64.b16decode(\n') + ind1 = indent + self._indent_per_level + chunksize = (16 if self._width - ind1 >= 68 else + 8 if self._width - ind1 >= 36 else + 4) + for chunk in _chunks(object, chunksize): + write(' ' * ind1) + hexes = b' '.join(_chunks(_base64.b16encode(chunk), 2)) + chars = re.sub(b'[^ -~]', b'.', chunk) + write('%-*r # %s\n' % (chunksize * 3 + 1, + hexes.decode('ascii'), + chars.decode('ascii'))) + write(' ' * indent) + write(".replace(' ', ''))") + return + write(rep) def _repr(self, object, context, level): diff -r 97522b189c79 Lib/test/test_pprint.py --- a/Lib/test/test_pprint.py Mon Apr 29 10:23:31 2013 -0400 +++ b/Lib/test/test_pprint.py Mon Apr 29 21:09:26 2013 +0300 @@ -513,6 +513,44 @@ formatted = pprint.pformat(special, width=width) self.assertEqual(eval("(" + formatted + ")"), special) + def test_bytes_hex(self): + data = bytes(range(0, 256, 5)) + self.assertEqual(pprint.pformat(data, width=80), """\ +base64.b16decode( + '00 05 0A 0F 14 19 1E 23 28 2D 32 37 3C 41 46 4B' # .......#(-27