home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 07 & 08 / pca1507.iso / Software / psp8 / Data1.cab / pprint.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  12.2 KB  |  355 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. """Support to pretty-print lists, tuples, & dictionaries recursively.
  5.  
  6. Very simple, but useful, especially in debugging data structures.
  7.  
  8. Classes
  9. -------
  10.  
  11. PrettyPrinter()
  12.     Handle pretty-printing operations onto a stream using a configured
  13.     set of formatting parameters.
  14.  
  15. Functions
  16. ---------
  17.  
  18. pformat()
  19.     Format a Python object into a pretty-printed representation.
  20.  
  21. pprint()
  22.     Pretty-print a Python object to a stream [default is sys.sydout].
  23.  
  24. saferepr()
  25.     Generate a 'standard' repr()-like value, but protect against recursive
  26.     data structures.
  27.  
  28. """
  29. from types import DictType, ListType, TupleType, StringType
  30. import sys
  31.  
  32. try:
  33.     from cStringIO import StringIO
  34. except ImportError:
  35.     from StringIO import StringIO
  36.  
  37. __all__ = [
  38.     'pprint',
  39.     'pformat',
  40.     'isreadable',
  41.     'isrecursive',
  42.     'saferepr',
  43.     'PrettyPrinter']
  44. _commajoin = ', '.join
  45. _sys_modules = sys.modules
  46. _id = id
  47. _len = len
  48. _type = type
  49.  
  50. def pprint(object, stream = None):
  51.     '''Pretty-print a Python object to a stream [default is sys.sydout].'''
  52.     printer = PrettyPrinter(stream = stream)
  53.     printer.pprint(object)
  54.  
  55.  
  56. def pformat(object):
  57.     '''Format a Python object into a pretty-printed representation.'''
  58.     return PrettyPrinter().pformat(object)
  59.  
  60.  
  61. def saferepr(object):
  62.     '''Version of repr() which can handle recursive data structures.'''
  63.     return _safe_repr(object, { }, None, 0)[0]
  64.  
  65.  
  66. def isreadable(object):
  67.     '''Determine if saferepr(object) is readable by eval().'''
  68.     return _safe_repr(object, { }, None, 0)[1]
  69.  
  70.  
  71. def isrecursive(object):
  72.     '''Determine if object requires a recursive representation.'''
  73.     return _safe_repr(object, { }, None, 0)[2]
  74.  
  75.  
  76. class PrettyPrinter:
  77.     
  78.     def __init__(self, indent = 1, width = 80, depth = None, stream = None):
  79.         '''Handle pretty printing operations onto a stream using a set of
  80.         configured parameters.
  81.  
  82.         indent
  83.             Number of spaces to indent for each level of nesting.
  84.  
  85.         width
  86.             Attempted maximum number of columns in the output.
  87.  
  88.         depth
  89.             The maximum depth to print out nested structures.
  90.  
  91.         stream
  92.             The desired output stream.  If omitted (or false), the standard
  93.             output stream available at construction will be used.
  94.  
  95.         '''
  96.         indent = int(indent)
  97.         width = int(width)
  98.         if not __debug__ and indent >= 0:
  99.             raise AssertionError
  100.         if __debug__:
  101.             if not depth is None or depth > 0:
  102.                 raise AssertionError, 'depth must be > 0'
  103.         if not __debug__ and width:
  104.             raise AssertionError
  105.         self._PrettyPrinter__depth = depth
  106.         self._PrettyPrinter__indent_per_level = indent
  107.         self._PrettyPrinter__width = width
  108.         if stream:
  109.             self._PrettyPrinter__stream = stream
  110.         else:
  111.             self._PrettyPrinter__stream = sys.stdout
  112.  
  113.     
  114.     def pprint(self, object):
  115.         self._PrettyPrinter__stream.write(self.pformat(object) + '\n')
  116.  
  117.     
  118.     def pformat(self, object):
  119.         sio = StringIO()
  120.         self._PrettyPrinter__format(object, sio, 0, 0, { }, 0)
  121.         return sio.getvalue()
  122.  
  123.     
  124.     def isrecursive(self, object):
  125.         self._PrettyPrinter__recursive = 0
  126.         self._PrettyPrinter__repr(object, { }, 0)
  127.         return self._PrettyPrinter__recursive
  128.  
  129.     
  130.     def isreadable(self, object):
  131.         self._PrettyPrinter__recursive = 0
  132.         self._PrettyPrinter__readable = 1
  133.         self._PrettyPrinter__repr(object, { }, 0)
  134.         if self._PrettyPrinter__readable:
  135.             pass
  136.         return not (self._PrettyPrinter__recursive)
  137.  
  138.     
  139.     def __format(self, object, stream, indent, allowance, context, level):
  140.         level = level + 1
  141.         objid = _id(object)
  142.         if objid in context:
  143.             stream.write(_recursion(object))
  144.             self._PrettyPrinter__recursive = 1
  145.             self._PrettyPrinter__readable = 0
  146.             return None
  147.         
  148.         rep = self._PrettyPrinter__repr(object, context, level - 1)
  149.         typ = _type(object)
  150.         sepLines = _len(rep) > self._PrettyPrinter__width - 1 - indent - allowance
  151.         write = stream.write
  152.         if sepLines:
  153.             if typ is DictType:
  154.                 write('{')
  155.                 if self._PrettyPrinter__indent_per_level > 1:
  156.                     write((self._PrettyPrinter__indent_per_level - 1) * ' ')
  157.                 
  158.                 length = _len(object)
  159.                 if length:
  160.                     context[objid] = 1
  161.                     indent = indent + self._PrettyPrinter__indent_per_level
  162.                     items = object.items()
  163.                     items.sort()
  164.                     (key, ent) = items[0]
  165.                     rep = self._PrettyPrinter__repr(key, context, level)
  166.                     write(rep)
  167.                     write(': ')
  168.                     self._PrettyPrinter__format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level)
  169.                     if length > 1:
  170.                         for key, ent in items[1:]:
  171.                             rep = self._PrettyPrinter__repr(key, context, level)
  172.                             write(',\n%s%s: ' % (' ' * indent, rep))
  173.                             self._PrettyPrinter__format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level)
  174.                         
  175.                     
  176.                     indent = indent - self._PrettyPrinter__indent_per_level
  177.                     del context[objid]
  178.                 
  179.                 write('}')
  180.                 return None
  181.             
  182.             if typ is ListType or typ is TupleType:
  183.                 if typ is ListType:
  184.                     write('[')
  185.                     endchar = ']'
  186.                 else:
  187.                     write('(')
  188.                     endchar = ')'
  189.                 if self._PrettyPrinter__indent_per_level > 1:
  190.                     write((self._PrettyPrinter__indent_per_level - 1) * ' ')
  191.                 
  192.                 length = _len(object)
  193.                 if length:
  194.                     context[objid] = 1
  195.                     indent = indent + self._PrettyPrinter__indent_per_level
  196.                     self._PrettyPrinter__format(object[0], stream, indent, allowance + 1, context, level)
  197.                     if length > 1:
  198.                         for ent in object[1:]:
  199.                             write(',\n' + ' ' * indent)
  200.                             self._PrettyPrinter__format(ent, stream, indent, allowance + 1, context, level)
  201.                         
  202.                     
  203.                     indent = indent - self._PrettyPrinter__indent_per_level
  204.                     del context[objid]
  205.                 
  206.                 if typ is TupleType and length == 1:
  207.                     write(',')
  208.                 
  209.                 write(endchar)
  210.                 return None
  211.             
  212.         
  213.         write(rep)
  214.  
  215.     
  216.     def __repr(self, object, context, level):
  217.         (repr, readable, recursive) = _safe_repr(object, context, self._PrettyPrinter__depth, level)
  218.         if not readable:
  219.             self._PrettyPrinter__readable = 0
  220.         
  221.         if recursive:
  222.             self._PrettyPrinter__recursive = 1
  223.         
  224.         return repr
  225.  
  226.  
  227.  
  228. def _safe_repr(object, context, maxlevels, level):
  229.     typ = _type(object)
  230.     if typ is StringType:
  231.         if 'locale' not in _sys_modules:
  232.             return (`object`, 1, 0)
  233.         
  234.         if "'" in object and '"' not in object:
  235.             closure = '"'
  236.             quotes = {
  237.                 '"': '\\"' }
  238.         else:
  239.             closure = "'"
  240.             quotes = {
  241.                 "'": "\\'" }
  242.         qget = quotes.get
  243.         sio = StringIO()
  244.         write = sio.write
  245.         for char in object:
  246.             if char.isalpha():
  247.                 write(char)
  248.             else:
  249.                 write(qget(char, `char`[1:-1]))
  250.         
  251.         return ('%s%s%s' % (closure, sio.getvalue(), closure), 1, 0)
  252.     
  253.     if typ is DictType:
  254.         if not object:
  255.             return ('{}', 1, 0)
  256.         
  257.         objid = _id(object)
  258.         if maxlevels and level > maxlevels:
  259.             return ('{...}', 0, objid in context)
  260.         
  261.         if objid in context:
  262.             return (_recursion(object), 0, 1)
  263.         
  264.         context[objid] = 1
  265.         readable = 1
  266.         recursive = 0
  267.         components = []
  268.         append = components.append
  269.         level += 1
  270.         saferepr = _safe_repr
  271.         for k, v in object.iteritems():
  272.             (krepr, kreadable, krecur) = saferepr(k, context, maxlevels, level)
  273.             (vrepr, vreadable, vrecur) = saferepr(v, context, maxlevels, level)
  274.             append('%s: %s' % (krepr, vrepr))
  275.             if readable and kreadable:
  276.                 pass
  277.             readable = vreadable
  278.             if krecur or vrecur:
  279.                 recursive = 1
  280.             
  281.         
  282.         del context[objid]
  283.         return ('{%s}' % _commajoin(components), readable, recursive)
  284.     
  285.     if typ is ListType or typ is TupleType:
  286.         if typ is ListType:
  287.             if not object:
  288.                 return ('[]', 1, 0)
  289.             
  290.             format = '[%s]'
  291.         elif _len(object) == 1:
  292.             format = '(%s,)'
  293.         elif not object:
  294.             return ('()', 1, 0)
  295.         
  296.         format = '(%s)'
  297.         objid = _id(object)
  298.         if maxlevels and level > maxlevels:
  299.             return (format % '...', 0, objid in context)
  300.         
  301.         if objid in context:
  302.             return (_recursion(object), 0, 1)
  303.         
  304.         context[objid] = 1
  305.         readable = 1
  306.         recursive = 0
  307.         components = []
  308.         append = components.append
  309.         level += 1
  310.         for o in object:
  311.             (orepr, oreadable, orecur) = _safe_repr(o, context, maxlevels, level)
  312.             append(orepr)
  313.             if not oreadable:
  314.                 readable = 0
  315.             
  316.             if orecur:
  317.                 recursive = 1
  318.             
  319.         
  320.         del context[objid]
  321.         return (format % _commajoin(components), readable, recursive)
  322.     
  323.     rep = `object`
  324.     if rep:
  325.         pass
  326.     return (rep, not rep.startswith('<'), 0)
  327.  
  328.  
  329. def _recursion(object):
  330.     return '<Recursion on %s with id=%s>' % (_type(object).__name__, _id(object))
  331.  
  332.  
  333. def _perfcheck(object = None):
  334.     import time
  335.     if object is None:
  336.         object = [
  337.             ('string', (1, 2), [
  338.                 3,
  339.                 4], {
  340.                 5: 6,
  341.                 7: 8 })] * 100000
  342.     
  343.     p = PrettyPrinter()
  344.     t1 = time.time()
  345.     _safe_repr(object, { }, None, 0)
  346.     t2 = time.time()
  347.     p.pformat(object)
  348.     t3 = time.time()
  349.     print '_safe_repr:', t2 - t1
  350.     print 'pformat:', t3 - t2
  351.  
  352. if __name__ == '__main__':
  353.     _perfcheck()
  354.  
  355.