# 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
from cStringIO import StringIO as _StringIO
from StringIO import StringIO as _StringIO
__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
# cache these for faster access:
def pprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
stream=stream, indent=indent, width=width, depth=depth)
def pformat(object, indent=1, width=80, depth=None):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
"""Version of repr() which can handle recursive data structures."""
return _safe_repr(object, {}, None, 0)[0]
"""Determine if saferepr(object) is readable by eval()."""
return _safe_repr(object, {}, None, 0)[1]
"""Determine if object requires a recursive representation."""
return _safe_repr(object, {}, None, 0)[2]
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "comparing unequal types "
"not supported", DeprecationWarning)
def __init__(self, indent=1, width=80, depth=None, stream=None):
"""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.
assert indent >= 0, "indent must be >= 0"
assert depth is None or depth > 0, "depth must be > 0"
assert width, "width must be != 0"
self._indent_per_level = indent
self._stream = _sys.stdout
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 - 1)
sepLines = _len(rep) > (self._width - 1 - indent - allowance)
if self._depth and level > self._depth:
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__:
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
indent = indent + self._indent_per_level
items = _sorted(object.items())
rep = self._repr(key, context, level)
self._format(ent, stream, indent + _len(rep) + 2,
allowance + 1, context, level)
for key, ent in items[1:]:
rep = self._repr(key, context, level)
write(',\n%s%s: ' % (' '*indent, rep))
self._format(ent, stream, indent + _len(rep) + 2,
allowance + 1, context, level)
indent = indent - self._indent_per_level
if ((issubclass(typ, list) and r is list.__repr__) or
(issubclass(typ, tuple) and r is tuple.__repr__) or
(issubclass(typ, set) and r is set.__repr__) or
(issubclass(typ, frozenset) and r is frozenset.__repr__)
if issubclass(typ, list):
elif issubclass(typ, tuple):
indent += len(typ.__name__) + 1
if self._indent_per_level > 1 and sepLines:
write((self._indent_per_level - 1) * ' ')
indent = indent + self._indent_per_level
self._format(object[0], stream, indent, allowance + 1,
write(',\n' + ' '*indent)
self._format(ent, stream, indent,
allowance + 1, context, level)
indent = indent - self._indent_per_level
if issubclass(typ, tuple) and length == 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)
# Return triple (repr_string, isreadable, isrecursive).
def _safe_repr(object, context, maxlevels, level):
if 'locale' not in _sys.modules:
return repr(object), True, False
if "'" in object and '"' not in object:
write(qget(char, repr(char)[1:-1]))
return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__:
if maxlevels and level >= maxlevels:
return "{...}", False, objid in context
return _recursion(object), False, True
append = components.append
for k, v in _sorted(object.items()):
krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
append("%s: %s" % (krepr, vrepr))
readable = readable and kreadable and vreadable
return "{%s}" % _commajoin(components), readable, recursive
if (issubclass(typ, list) and r is list.__repr__) or \
(issubclass(typ, tuple) and r is tuple.__repr__):
if issubclass(typ, list):
if maxlevels and level >= maxlevels:
return format % "...", False, objid in context
return _recursion(object), False, True
append = components.append
orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
return format % _commajoin(components), readable, recursive
return rep, (rep and not rep.startswith('<')), False
return ("<Recursion on %s with id=%s>"
% (_type(object).__name__, _id(object)))
def _perfcheck(object=None):
object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
_safe_repr(object, {}, None, 0)
print "_safe_repr:", t2 - t1
print "pformat:", t3 - t2
if __name__ == "__main__":