# Author: Fred L. Drake, Jr.
# This is a simple little module I wrote to make life easier. I didn't
# see anything quite like it in the library, though I may have overlooked
# something. I wrote this when I was trying to read some heavily nested
# tuples with fairly non-descriptive content. This is modeled very much
# after Lisp/Scheme - style pretty-printing of lists. If you find it
# useful, thank small children who sleep at night.
"""Support to pretty-print lists, tuples, & dictionaries recursively.
Very simple, but useful, especially in debugging data structures.
Handle pretty-printing operations onto a stream using a configured
set of formatting parameters.
Format a Python object into a pretty-printed representation.
Pretty-print a Python object to a stream [default is sys.stdout].
Generate a 'standard' repr()-like value, but protect against recursive
import collections as _collections
from io import StringIO as _StringIO
__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
def pprint(object, stream=None, indent=1, width=80, depth=None, *,
compact=False, sort_dicts=True):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
stream=stream, indent=indent, width=width, depth=depth,
compact=compact, sort_dicts=sort_dicts)
def pformat(object, indent=1, width=80, depth=None, *,
compact=False, sort_dicts=True):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth,
compact=compact, sort_dicts=sort_dicts).pformat(object)
def pp(object, *args, sort_dicts=False, **kwargs):
"""Pretty-print a Python object"""
pprint(object, *args, sort_dicts=sort_dicts, **kwargs)
"""Version of repr() which can handle recursive data structures."""
return _safe_repr(object, {}, None, 0, True)[0]
"""Determine if saferepr(object) is readable by eval()."""
return _safe_repr(object, {}, None, 0, True)[1]
"""Determine if object requires a recursive representation."""
return _safe_repr(object, {}, None, 0, True)[2]
"""Helper function for key functions when sorting unorderable objects.
The wrapped-object will fallback to a Py2.x style comparison for
unorderable types (sorting first comparing the type name and then by
the obj ids). Does not work recursively, so dict.items() must have
_safe_key applied to both the key and the value.
return self.obj < other.obj
return ((str(type(self.obj)), id(self.obj)) < \
(str(type(other.obj)), id(other.obj)))
"Helper function for comparing 2-tuples"
return _safe_key(t[0]), _safe_key(t[1])
def __init__(self, indent=1, width=80, depth=None, stream=None, *,
compact=False, sort_dicts=True):
"""Handle pretty printing operations onto a stream using a set of
Number of spaces to indent for each level of nesting.
Attempted maximum number of columns in the output.
The maximum depth to print out nested structures.
The desired output stream. If omitted (or false), the standard
output stream available at construction will be used.
If true, several items will be combined in one line.
If true, dict keys are sorted.
raise ValueError('indent must be >= 0')
if depth is not None and depth <= 0:
raise ValueError('depth must be > 0')
raise ValueError('width must be != 0')
self._indent_per_level = indent
self._stream = _sys.stdout
self._compact = bool(compact)
self._sort_dicts = sort_dicts
def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
def pformat(self, object):
self._format(object, sio, 0, 0, {}, 0)
def isrecursive(self, object):
return self.format(object, {}, 0, 0)[2]
def isreadable(self, object):
s, readable, recursive = self.format(object, {}, 0, 0)
return readable and not recursive
def _format(self, object, stream, indent, allowance, context, level):
stream.write(_recursion(object))
rep = self._repr(object, context, level)
max_width = self._width - indent - allowance
p = self._dispatch.get(type(object).__repr__, None)
p(self, object, stream, indent, allowance, context, level + 1)
elif isinstance(object, dict):
self._pprint_dict(object, stream, indent, allowance,
def _pprint_dict(self, object, stream, indent, allowance, context, level):
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
items = sorted(object.items(), key=_safe_tuple)
self._format_dict_items(items, stream, indent, allowance + 1,
_dispatch[dict.__repr__] = _pprint_dict
def _pprint_ordered_dict(self, object, stream, indent, allowance, context, level):
stream.write(repr(object))
stream.write(cls.__name__ + '(')
self._format(list(object.items()), stream,
indent + len(cls.__name__) + 1, allowance + 1,
_dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict
def _pprint_list(self, object, stream, indent, allowance, context, level):
self._format_items(object, stream, indent, allowance + 1,
_dispatch[list.__repr__] = _pprint_list
def _pprint_tuple(self, object, stream, indent, allowance, context, level):
endchar = ',)' if len(object) == 1 else ')'
self._format_items(object, stream, indent, allowance + len(endchar),
_dispatch[tuple.__repr__] = _pprint_tuple
def _pprint_set(self, object, stream, indent, allowance, context, level):
stream.write(repr(object))
stream.write(typ.__name__ + '({')
indent += len(typ.__name__) + 1
object = sorted(object, key=_safe_key)
self._format_items(object, stream, indent, allowance + len(endchar),
_dispatch[set.__repr__] = _pprint_set
_dispatch[frozenset.__repr__] = _pprint_set
def _pprint_str(self, object, stream, indent, allowance, context, level):
lines = object.splitlines(True)
max_width1 = max_width = self._width - indent
for i, line in enumerate(lines):
if len(rep) <= max_width1:
# A list of alternating (non-space, space) strings
parts = re.findall(r'\S*\s*', line)
parts.pop() # drop empty last part
for j, part in enumerate(parts):
candidate = current + part
if j == len(parts) - 1 and i == len(lines) - 1:
if len(repr(candidate)) > max_width2:
chunks.append(repr(current))
chunks.append(repr(current))
for i, rep in enumerate(chunks):
_dispatch[str.__repr__] = _pprint_str
def _pprint_bytes(self, object, stream, indent, allowance, context, level):
for rep in _wrap_bytes_repr(object, self._width - indent, allowance):
delim = '\n' + ' '*indent
_dispatch[bytes.__repr__] = _pprint_bytes
def _pprint_bytearray(self, object, stream, indent, allowance, context, level):
self._pprint_bytes(bytes(object), stream, indent + 10,
allowance + 1, context, level + 1)
_dispatch[bytearray.__repr__] = _pprint_bytearray
def _pprint_mappingproxy(self, object, stream, indent, allowance, context, level):
stream.write('mappingproxy(')
self._format(object.copy(), stream, indent + 13, allowance + 1,
_dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
def _format_dict_items(self, items, stream, indent, allowance, context,
indent += self._indent_per_level
delimnl = ',\n' + ' ' * indent
last_index = len(items) - 1
for i, (key, ent) in enumerate(items):
rep = self._repr(key, context, level)
self._format(ent, stream, indent + len(rep) + 2,
allowance if last else 1,
def _format_items(self, items, stream, indent, allowance, context, level):
indent += self._indent_per_level
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
delimnl = ',\n' + ' ' * indent
width = max_width = self._width - indent + 1
rep = self._repr(ent, context, level)
self._format(ent, stream, indent,
allowance if last else 1,
def _repr(self, object, context, level):
repr, readable, recursive = self.format(object, context.copy(),
def format(self, object, context, maxlevels, level):
"""Format object for a specific context, returning a string
and flags indicating whether the representation is 'readable'
and whether the object represents a recursive construct.
return _safe_repr(object, context, maxlevels, level, self._sort_dicts)
def _pprint_default_dict(self, object, stream, indent, allowance, context, level):
stream.write(repr(object))
rdf = self._repr(object.default_factory, context, level)
indent += len(cls.__name__) + 1
stream.write('%s(%s,\n%s' % (cls.__name__, rdf, ' ' * indent))
self._pprint_dict(object, stream, indent, allowance + 1, context, level)
_dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict
def _pprint_counter(self, object, stream, indent, allowance, context, level):
stream.write(repr(object))
stream.write(cls.__name__ + '({')
if self._indent_per_level > 1:
stream.write((self._indent_per_level - 1) * ' ')
items = object.most_common()
self._format_dict_items(items, stream,
indent + len(cls.__name__) + 1, allowance + 2,
_dispatch[_collections.Counter.__repr__] = _pprint_counter
def _pprint_chain_map(self, object, stream, indent, allowance, context, level):
stream.write(repr(object))
stream.write(cls.__name__ + '(')
indent += len(cls.__name__) + 1
for i, m in enumerate(object.maps):
if i == len(object.maps) - 1:
self._format(m, stream, indent, allowance + 1, context, level)
self._format(m, stream, indent, 1, context, level)
stream.write(',\n' + ' ' * indent)
_dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map
def _pprint_deque(self, object, stream, indent, allowance, context, level):
stream.write(repr(object))
stream.write(cls.__name__ + '(')
indent += len(cls.__name__) + 1
if object.maxlen is None:
self._format_items(object, stream, indent, allowance + 2,
self._format_items(object, stream, indent, 2,
rml = self._repr(object.maxlen, context, level)
stream.write('],\n%smaxlen=%s)' % (' ' * indent, rml))
_dispatch[_collections.deque.__repr__] = _pprint_deque
def _pprint_user_dict(self, object, stream, indent, allowance, context, level):
self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserDict.__repr__] = _pprint_user_dict
def _pprint_user_list(self, object, stream, indent, allowance, context, level):
self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserList.__repr__] = _pprint_user_list
def _pprint_user_string(self, object, stream, indent, allowance, context, level):
self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserString.__repr__] = _pprint_user_string
# Return triple (repr_string, isreadable, isrecursive).