# Author: Fred L. Drake, Jr.# fdrake@acm.org## 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.Classes-------PrettyPrinter() Handle pretty-printing operations onto a stream using a configured set of formatting parameters.Functions---------pformat() Format a Python object into a pretty-printed representation.pprint() Pretty-print a Python object to a stream [default is sys.sydout].saferepr() Generate a 'standard' repr()-like value, but protect against recursive data structures."""fromtypesimportDictType,ListType,TupleType,StringTypeimportsystry:fromcStringIOimportStringIOexceptImportError:fromStringIOimportStringIO__all__=["pprint","pformat","isreadable","isrecursive","saferepr","PrettyPrinter"]# cache these for faster access:_commajoin=", ".join_sys_modules=sys.modules_id=id_len=len_type=typedefpprint(object,stream=None):"""Pretty-print a Python object to a stream [default is sys.sydout]."""printer=PrettyPrinter(stream=stream)printer.pprint(object)defpformat(object):"""Format a Python object into a pretty-printed representation."""returnPrettyPrinter().pformat(object)defsaferepr(object):"""Version of repr() which can handle recursive data structures."""return_safe_repr(object,{},None,0)[0]defisreadable(object):"""Determine if saferepr(object) is readable by eval()."""return_safe_repr(object,{},None,0)[1]defisrecursive(object):"""Determine if object requires a recursive representation."""return_safe_repr(object,{},None,0)[2]classPrettyPrinter:def__init__(self,indent=1,width=80,depth=None,stream=None):"""Handle pretty printing operations onto a stream using a set of configured parameters. indent Number of spaces to indent for each level of nesting. width Attempted maximum number of columns in the output. depth The maximum depth to print out nested structures. stream The desired output stream. If omitted (or false), the standard output stream available at construction will be used. """indent=int(indent)width=int(width)assertindent>=0assertdepthisNoneordepth>0,"depth must be > 0"assertwidthself.__depth=depthself.__indent_per_level=indentself.__width=widthifstream:self.__stream=streamelse:self.__stream=sys.stdoutdefpprint(self,object):self.__stream.write(self.pformat(object)+"\n")defpformat(self,object):sio=StringIO()self.__format(object,sio,0,0,{},0)returnsio.getvalue()defisrecursive(self,object):self.__recursive=0self.__repr(object,{},0)returnself.__recursivedefisreadable(self,object):self.__recursive=0self.__readable=1self.__repr(object,{},0)returnself.__readableandnotself.__recursivedef__format(self,object,stream,indent,allowance,context,level):level=level+1objid=_id(object)ifobjidincontext:stream.write(_recursion(object))self.__recursive=1self.__readable=0returnrep=self.__repr(object,context,level-1)typ=_type(object)sepLines=_len(rep)>(self.__width-1-indent-allowance)write=stream.writeifsepLines:iftypisDictType:write('{')ifself.__indent_per_level>1:write((self.__indent_per_level-1)*' ')length=_len(object)iflength:context[objid]=1indent=indent+self.__indent_per_levelitems=object.items()items.sort()key,ent=items[0]rep=self.__repr(key,context,level)write(rep)write(': ')self.__format(ent,stream,indent+_len(rep)+2,allowance+1,context,level)iflength>1:forkey,entinitems[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_leveldelcontext[objid]write('}')returniftypisListTypeortypisTupleType:iftypisListType:write('[')endchar=']'else:write('(')endchar=')'ifself.__indent_per_level>1:write((self.__indent_per_level-1)*' ')length=_len(object)iflength:context[objid]=1indent=indent+self.__indent_per_levelself.__format(object[0],stream,indent,allowance+1,context,level)iflength>1:forentinobject[1:]:write(',\n'+' '*indent)self.__format(ent,stream,indent,allowance+1,context,level)indent=indent-self.__indent_per_leveldelcontext[objid]iftypisTupleTypeandlength==1:write(',')write(endchar)returnwrite(rep)def__repr(self,object,context,level):repr,readable,recursive=_safe_repr(object,context,self.__depth,level)ifnotreadable:self.__readable=0ifrecursive:self.__recursive=1returnrepr# Return triple (repr_string, isreadable, isrecursive).def_safe_repr(object,context,maxlevels,level):typ=_type(object)iftypisStringType:if'locale'notin_sys_modules:return`object`,1,0if"'"inobjectand'"'notinobject:closure='"'quotes={'"':'\\"'}else:closure="'"quotes={"'":"\\'"}qget=quotes.getsio=StringIO()write=sio.writeforcharinobject:ifchar.isalpha():write(char)else:write(qget(char,`char`[1:-1]))return("%s%s%s"%(closure,sio.getvalue(),closure)),1,0iftypisDictType:ifnotobject:return"{}",1,0objid=_id(object)ifmaxlevelsandlevel>maxlevels:return"{...}",0,objidincontextifobjidincontext:return_recursion(object),0,1context[objid]=1readable=1recursive=0components=[]append=components.appendlevel+=1saferepr=_safe_reprfork,vinobject.iteritems():krepr,kreadable,krecur=saferepr(k,context,maxlevels,level)vrepr,vreadable,vrecur=saferepr(v,context,maxlevels,level)append("%s: %s"%(krepr,vrepr))readable=readableandkreadableandvreadableifkrecurorvrecur:recursive=1delcontext[objid]return"{%s}"%_commajoin(components),readable,recursiveiftypisListTypeortypisTupleType:iftypisListType:ifnotobject:return"[]",1,0format="[%s]"elif_len(object)==1:format="(%s,)"else:ifnotobject:return"()",1,0format="(%s)"objid=_id(object)ifmaxlevelsandlevel>maxlevels:returnformat%"...",0,objidincontextifobjidincontext:return_recursion(object),0,1context[objid]=1readable=1recursive=0components=[]append=components.appendlevel+=1foroinobject:orepr,oreadable,orecur=_safe_repr(o,context,maxlevels,level)append(orepr)ifnotoreadable:readable=0iforecur:recursive=1delcontext[objid]returnformat%_commajoin(components),readable,recursiverep=`object`returnrep,(repandnotrep.startswith('<')),0def_recursion(object):return("<Recursion on %s with id=%s>"%(_type(object).__name__,_id(object)))def_perfcheck(object=None):importtimeifobjectisNone:object=[("string",(1,2),[3,4],{5:6,7:8})]*100000p=PrettyPrinter()t1=time.time()_safe_repr(object,{},None,0)t2=time.time()p.pformat(object)t3=time.time()print"_safe_repr:",t2-t1print"pformat:",t3-t2if__name__=="__main__":_perfcheck()