Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python2....
File: pprint.py
# Author: Fred L. Drake, Jr.
[0] Fix | Delete
# fdrake@acm.org
[1] Fix | Delete
#
[2] Fix | Delete
# This is a simple little module I wrote to make life easier. I didn't
[3] Fix | Delete
# see anything quite like it in the library, though I may have overlooked
[4] Fix | Delete
# something. I wrote this when I was trying to read some heavily nested
[5] Fix | Delete
# tuples with fairly non-descriptive content. This is modeled very much
[6] Fix | Delete
# after Lisp/Scheme - style pretty-printing of lists. If you find it
[7] Fix | Delete
# useful, thank small children who sleep at night.
[8] Fix | Delete
[9] Fix | Delete
"""Support to pretty-print lists, tuples, & dictionaries recursively.
[10] Fix | Delete
[11] Fix | Delete
Very simple, but useful, especially in debugging data structures.
[12] Fix | Delete
[13] Fix | Delete
Classes
[14] Fix | Delete
-------
[15] Fix | Delete
[16] Fix | Delete
PrettyPrinter()
[17] Fix | Delete
Handle pretty-printing operations onto a stream using a configured
[18] Fix | Delete
set of formatting parameters.
[19] Fix | Delete
[20] Fix | Delete
Functions
[21] Fix | Delete
---------
[22] Fix | Delete
[23] Fix | Delete
pformat()
[24] Fix | Delete
Format a Python object into a pretty-printed representation.
[25] Fix | Delete
[26] Fix | Delete
pprint()
[27] Fix | Delete
Pretty-print a Python object to a stream [default is sys.stdout].
[28] Fix | Delete
[29] Fix | Delete
saferepr()
[30] Fix | Delete
Generate a 'standard' repr()-like value, but protect against recursive
[31] Fix | Delete
data structures.
[32] Fix | Delete
[33] Fix | Delete
"""
[34] Fix | Delete
[35] Fix | Delete
import sys as _sys
[36] Fix | Delete
import warnings
[37] Fix | Delete
[38] Fix | Delete
try:
[39] Fix | Delete
from cStringIO import StringIO as _StringIO
[40] Fix | Delete
except ImportError:
[41] Fix | Delete
from StringIO import StringIO as _StringIO
[42] Fix | Delete
[43] Fix | Delete
__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
[44] Fix | Delete
"PrettyPrinter"]
[45] Fix | Delete
[46] Fix | Delete
# cache these for faster access:
[47] Fix | Delete
_commajoin = ", ".join
[48] Fix | Delete
_id = id
[49] Fix | Delete
_len = len
[50] Fix | Delete
_type = type
[51] Fix | Delete
[52] Fix | Delete
[53] Fix | Delete
def pprint(object, stream=None, indent=1, width=80, depth=None):
[54] Fix | Delete
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
[55] Fix | Delete
printer = PrettyPrinter(
[56] Fix | Delete
stream=stream, indent=indent, width=width, depth=depth)
[57] Fix | Delete
printer.pprint(object)
[58] Fix | Delete
[59] Fix | Delete
def pformat(object, indent=1, width=80, depth=None):
[60] Fix | Delete
"""Format a Python object into a pretty-printed representation."""
[61] Fix | Delete
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
[62] Fix | Delete
[63] Fix | Delete
def saferepr(object):
[64] Fix | Delete
"""Version of repr() which can handle recursive data structures."""
[65] Fix | Delete
return _safe_repr(object, {}, None, 0)[0]
[66] Fix | Delete
[67] Fix | Delete
def isreadable(object):
[68] Fix | Delete
"""Determine if saferepr(object) is readable by eval()."""
[69] Fix | Delete
return _safe_repr(object, {}, None, 0)[1]
[70] Fix | Delete
[71] Fix | Delete
def isrecursive(object):
[72] Fix | Delete
"""Determine if object requires a recursive representation."""
[73] Fix | Delete
return _safe_repr(object, {}, None, 0)[2]
[74] Fix | Delete
[75] Fix | Delete
def _sorted(iterable):
[76] Fix | Delete
with warnings.catch_warnings():
[77] Fix | Delete
if _sys.py3kwarning:
[78] Fix | Delete
warnings.filterwarnings("ignore", "comparing unequal types "
[79] Fix | Delete
"not supported", DeprecationWarning)
[80] Fix | Delete
return sorted(iterable)
[81] Fix | Delete
[82] Fix | Delete
class PrettyPrinter:
[83] Fix | Delete
def __init__(self, indent=1, width=80, depth=None, stream=None):
[84] Fix | Delete
"""Handle pretty printing operations onto a stream using a set of
[85] Fix | Delete
configured parameters.
[86] Fix | Delete
[87] Fix | Delete
indent
[88] Fix | Delete
Number of spaces to indent for each level of nesting.
[89] Fix | Delete
[90] Fix | Delete
width
[91] Fix | Delete
Attempted maximum number of columns in the output.
[92] Fix | Delete
[93] Fix | Delete
depth
[94] Fix | Delete
The maximum depth to print out nested structures.
[95] Fix | Delete
[96] Fix | Delete
stream
[97] Fix | Delete
The desired output stream. If omitted (or false), the standard
[98] Fix | Delete
output stream available at construction will be used.
[99] Fix | Delete
[100] Fix | Delete
"""
[101] Fix | Delete
indent = int(indent)
[102] Fix | Delete
width = int(width)
[103] Fix | Delete
assert indent >= 0, "indent must be >= 0"
[104] Fix | Delete
assert depth is None or depth > 0, "depth must be > 0"
[105] Fix | Delete
assert width, "width must be != 0"
[106] Fix | Delete
self._depth = depth
[107] Fix | Delete
self._indent_per_level = indent
[108] Fix | Delete
self._width = width
[109] Fix | Delete
if stream is not None:
[110] Fix | Delete
self._stream = stream
[111] Fix | Delete
else:
[112] Fix | Delete
self._stream = _sys.stdout
[113] Fix | Delete
[114] Fix | Delete
def pprint(self, object):
[115] Fix | Delete
self._format(object, self._stream, 0, 0, {}, 0)
[116] Fix | Delete
self._stream.write("\n")
[117] Fix | Delete
[118] Fix | Delete
def pformat(self, object):
[119] Fix | Delete
sio = _StringIO()
[120] Fix | Delete
self._format(object, sio, 0, 0, {}, 0)
[121] Fix | Delete
return sio.getvalue()
[122] Fix | Delete
[123] Fix | Delete
def isrecursive(self, object):
[124] Fix | Delete
return self.format(object, {}, 0, 0)[2]
[125] Fix | Delete
[126] Fix | Delete
def isreadable(self, object):
[127] Fix | Delete
s, readable, recursive = self.format(object, {}, 0, 0)
[128] Fix | Delete
return readable and not recursive
[129] Fix | Delete
[130] Fix | Delete
def _format(self, object, stream, indent, allowance, context, level):
[131] Fix | Delete
level = level + 1
[132] Fix | Delete
objid = _id(object)
[133] Fix | Delete
if objid in context:
[134] Fix | Delete
stream.write(_recursion(object))
[135] Fix | Delete
self._recursive = True
[136] Fix | Delete
self._readable = False
[137] Fix | Delete
return
[138] Fix | Delete
rep = self._repr(object, context, level - 1)
[139] Fix | Delete
typ = _type(object)
[140] Fix | Delete
sepLines = _len(rep) > (self._width - 1 - indent - allowance)
[141] Fix | Delete
write = stream.write
[142] Fix | Delete
[143] Fix | Delete
if self._depth and level > self._depth:
[144] Fix | Delete
write(rep)
[145] Fix | Delete
return
[146] Fix | Delete
[147] Fix | Delete
r = getattr(typ, "__repr__", None)
[148] Fix | Delete
if issubclass(typ, dict) and r is dict.__repr__:
[149] Fix | Delete
write('{')
[150] Fix | Delete
if self._indent_per_level > 1:
[151] Fix | Delete
write((self._indent_per_level - 1) * ' ')
[152] Fix | Delete
length = _len(object)
[153] Fix | Delete
if length:
[154] Fix | Delete
context[objid] = 1
[155] Fix | Delete
indent = indent + self._indent_per_level
[156] Fix | Delete
items = _sorted(object.items())
[157] Fix | Delete
key, ent = items[0]
[158] Fix | Delete
rep = self._repr(key, context, level)
[159] Fix | Delete
write(rep)
[160] Fix | Delete
write(': ')
[161] Fix | Delete
self._format(ent, stream, indent + _len(rep) + 2,
[162] Fix | Delete
allowance + 1, context, level)
[163] Fix | Delete
if length > 1:
[164] Fix | Delete
for key, ent in items[1:]:
[165] Fix | Delete
rep = self._repr(key, context, level)
[166] Fix | Delete
if sepLines:
[167] Fix | Delete
write(',\n%s%s: ' % (' '*indent, rep))
[168] Fix | Delete
else:
[169] Fix | Delete
write(', %s: ' % rep)
[170] Fix | Delete
self._format(ent, stream, indent + _len(rep) + 2,
[171] Fix | Delete
allowance + 1, context, level)
[172] Fix | Delete
indent = indent - self._indent_per_level
[173] Fix | Delete
del context[objid]
[174] Fix | Delete
write('}')
[175] Fix | Delete
return
[176] Fix | Delete
[177] Fix | Delete
if ((issubclass(typ, list) and r is list.__repr__) or
[178] Fix | Delete
(issubclass(typ, tuple) and r is tuple.__repr__) or
[179] Fix | Delete
(issubclass(typ, set) and r is set.__repr__) or
[180] Fix | Delete
(issubclass(typ, frozenset) and r is frozenset.__repr__)
[181] Fix | Delete
):
[182] Fix | Delete
length = _len(object)
[183] Fix | Delete
if issubclass(typ, list):
[184] Fix | Delete
write('[')
[185] Fix | Delete
endchar = ']'
[186] Fix | Delete
elif issubclass(typ, tuple):
[187] Fix | Delete
write('(')
[188] Fix | Delete
endchar = ')'
[189] Fix | Delete
else:
[190] Fix | Delete
if not length:
[191] Fix | Delete
write(rep)
[192] Fix | Delete
return
[193] Fix | Delete
write(typ.__name__)
[194] Fix | Delete
write('([')
[195] Fix | Delete
endchar = '])'
[196] Fix | Delete
indent += len(typ.__name__) + 1
[197] Fix | Delete
object = _sorted(object)
[198] Fix | Delete
if self._indent_per_level > 1 and sepLines:
[199] Fix | Delete
write((self._indent_per_level - 1) * ' ')
[200] Fix | Delete
if length:
[201] Fix | Delete
context[objid] = 1
[202] Fix | Delete
indent = indent + self._indent_per_level
[203] Fix | Delete
self._format(object[0], stream, indent, allowance + 1,
[204] Fix | Delete
context, level)
[205] Fix | Delete
if length > 1:
[206] Fix | Delete
for ent in object[1:]:
[207] Fix | Delete
if sepLines:
[208] Fix | Delete
write(',\n' + ' '*indent)
[209] Fix | Delete
else:
[210] Fix | Delete
write(', ')
[211] Fix | Delete
self._format(ent, stream, indent,
[212] Fix | Delete
allowance + 1, context, level)
[213] Fix | Delete
indent = indent - self._indent_per_level
[214] Fix | Delete
del context[objid]
[215] Fix | Delete
if issubclass(typ, tuple) and length == 1:
[216] Fix | Delete
write(',')
[217] Fix | Delete
write(endchar)
[218] Fix | Delete
return
[219] Fix | Delete
[220] Fix | Delete
write(rep)
[221] Fix | Delete
[222] Fix | Delete
def _repr(self, object, context, level):
[223] Fix | Delete
repr, readable, recursive = self.format(object, context.copy(),
[224] Fix | Delete
self._depth, level)
[225] Fix | Delete
if not readable:
[226] Fix | Delete
self._readable = False
[227] Fix | Delete
if recursive:
[228] Fix | Delete
self._recursive = True
[229] Fix | Delete
return repr
[230] Fix | Delete
[231] Fix | Delete
def format(self, object, context, maxlevels, level):
[232] Fix | Delete
"""Format object for a specific context, returning a string
[233] Fix | Delete
and flags indicating whether the representation is 'readable'
[234] Fix | Delete
and whether the object represents a recursive construct.
[235] Fix | Delete
"""
[236] Fix | Delete
return _safe_repr(object, context, maxlevels, level)
[237] Fix | Delete
[238] Fix | Delete
[239] Fix | Delete
# Return triple (repr_string, isreadable, isrecursive).
[240] Fix | Delete
[241] Fix | Delete
def _safe_repr(object, context, maxlevels, level):
[242] Fix | Delete
typ = _type(object)
[243] Fix | Delete
if typ is str:
[244] Fix | Delete
if 'locale' not in _sys.modules:
[245] Fix | Delete
return repr(object), True, False
[246] Fix | Delete
if "'" in object and '"' not in object:
[247] Fix | Delete
closure = '"'
[248] Fix | Delete
quotes = {'"': '\\"'}
[249] Fix | Delete
else:
[250] Fix | Delete
closure = "'"
[251] Fix | Delete
quotes = {"'": "\\'"}
[252] Fix | Delete
qget = quotes.get
[253] Fix | Delete
sio = _StringIO()
[254] Fix | Delete
write = sio.write
[255] Fix | Delete
for char in object:
[256] Fix | Delete
if char.isalpha():
[257] Fix | Delete
write(char)
[258] Fix | Delete
else:
[259] Fix | Delete
write(qget(char, repr(char)[1:-1]))
[260] Fix | Delete
return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
[261] Fix | Delete
[262] Fix | Delete
r = getattr(typ, "__repr__", None)
[263] Fix | Delete
if issubclass(typ, dict) and r is dict.__repr__:
[264] Fix | Delete
if not object:
[265] Fix | Delete
return "{}", True, False
[266] Fix | Delete
objid = _id(object)
[267] Fix | Delete
if maxlevels and level >= maxlevels:
[268] Fix | Delete
return "{...}", False, objid in context
[269] Fix | Delete
if objid in context:
[270] Fix | Delete
return _recursion(object), False, True
[271] Fix | Delete
context[objid] = 1
[272] Fix | Delete
readable = True
[273] Fix | Delete
recursive = False
[274] Fix | Delete
components = []
[275] Fix | Delete
append = components.append
[276] Fix | Delete
level += 1
[277] Fix | Delete
saferepr = _safe_repr
[278] Fix | Delete
for k, v in _sorted(object.items()):
[279] Fix | Delete
krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
[280] Fix | Delete
vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
[281] Fix | Delete
append("%s: %s" % (krepr, vrepr))
[282] Fix | Delete
readable = readable and kreadable and vreadable
[283] Fix | Delete
if krecur or vrecur:
[284] Fix | Delete
recursive = True
[285] Fix | Delete
del context[objid]
[286] Fix | Delete
return "{%s}" % _commajoin(components), readable, recursive
[287] Fix | Delete
[288] Fix | Delete
if (issubclass(typ, list) and r is list.__repr__) or \
[289] Fix | Delete
(issubclass(typ, tuple) and r is tuple.__repr__):
[290] Fix | Delete
if issubclass(typ, list):
[291] Fix | Delete
if not object:
[292] Fix | Delete
return "[]", True, False
[293] Fix | Delete
format = "[%s]"
[294] Fix | Delete
elif _len(object) == 1:
[295] Fix | Delete
format = "(%s,)"
[296] Fix | Delete
else:
[297] Fix | Delete
if not object:
[298] Fix | Delete
return "()", True, False
[299] Fix | Delete
format = "(%s)"
[300] Fix | Delete
objid = _id(object)
[301] Fix | Delete
if maxlevels and level >= maxlevels:
[302] Fix | Delete
return format % "...", False, objid in context
[303] Fix | Delete
if objid in context:
[304] Fix | Delete
return _recursion(object), False, True
[305] Fix | Delete
context[objid] = 1
[306] Fix | Delete
readable = True
[307] Fix | Delete
recursive = False
[308] Fix | Delete
components = []
[309] Fix | Delete
append = components.append
[310] Fix | Delete
level += 1
[311] Fix | Delete
for o in object:
[312] Fix | Delete
orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
[313] Fix | Delete
append(orepr)
[314] Fix | Delete
if not oreadable:
[315] Fix | Delete
readable = False
[316] Fix | Delete
if orecur:
[317] Fix | Delete
recursive = True
[318] Fix | Delete
del context[objid]
[319] Fix | Delete
return format % _commajoin(components), readable, recursive
[320] Fix | Delete
[321] Fix | Delete
rep = repr(object)
[322] Fix | Delete
return rep, (rep and not rep.startswith('<')), False
[323] Fix | Delete
[324] Fix | Delete
[325] Fix | Delete
def _recursion(object):
[326] Fix | Delete
return ("<Recursion on %s with id=%s>"
[327] Fix | Delete
% (_type(object).__name__, _id(object)))
[328] Fix | Delete
[329] Fix | Delete
[330] Fix | Delete
def _perfcheck(object=None):
[331] Fix | Delete
import time
[332] Fix | Delete
if object is None:
[333] Fix | Delete
object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
[334] Fix | Delete
p = PrettyPrinter()
[335] Fix | Delete
t1 = time.time()
[336] Fix | Delete
_safe_repr(object, {}, None, 0)
[337] Fix | Delete
t2 = time.time()
[338] Fix | Delete
p.pformat(object)
[339] Fix | Delete
t3 = time.time()
[340] Fix | Delete
print "_safe_repr:", t2 - t1
[341] Fix | Delete
print "pformat:", t3 - t2
[342] Fix | Delete
[343] Fix | Delete
if __name__ == "__main__":
[344] Fix | Delete
_perfcheck()
[345] Fix | Delete
[346] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function