home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / OPENSTEP / Languages / Python / python-14-src / Demo / parser / pprint.py < prev    next >
Encoding:
Python Source  |  1997-01-17  |  3.9 KB  |  137 lines

  1. #  pprint.py
  2. #
  3. #  Author:    Fred L. Drake, Jr.
  4. #        fdrake@cnri.reston.va.us, fdrake@intr.net
  5. #
  6. #  This is a simple little module I wrote to make life easier.  I didn't
  7. #  see anything quite like it in the library, though I may have overlooked
  8. #  something.  I wrote this when I was trying to read some heavily nested
  9. #  tuples with fairly non-descriptive content.  This is modelled very much
  10. #  after Lisp/Scheme - style pretty-printing of lists.  If you find it
  11. #  useful, thank small children who sleep at night.
  12.  
  13. """Support to pretty-print lists, tuples, & dictionaries recursively.
  14. Very simple, but useful, especially in debugging data structures.
  15.  
  16. Constants
  17. ---------
  18.  
  19. INDENT_PER_LEVEL
  20.     Amount of indentation to use for each new recursive level.  The
  21.     default is 1.  This must be a non-negative integer, and may be set
  22.     by the caller before calling pprint().
  23.  
  24. MAX_WIDTH
  25.     Maximum width of the display.  This is only used if the
  26.     representation *can* be kept less than MAX_WIDTH characters wide.
  27.     May be set by the user before calling pprint().
  28.  
  29. TAB_WIDTH
  30.     The width represented by a single tab.  This value is typically 8,
  31.     but 4 is the default under MacOS.  Can be changed by the user if
  32.     desired, but is probably not a good idea.
  33. """
  34.  
  35. INDENT_PER_LEVEL = 1
  36.  
  37. MAX_WIDTH = 80
  38.  
  39. import os
  40. TAB_WIDTH = (os.name == 'mac' and 4) or 8
  41. del os
  42.  
  43. from types import DictType, ListType, TupleType
  44.  
  45.  
  46. def _indentation(cols):
  47.     """Create tabbed indentation string.
  48.  
  49.     cols
  50.     Width of the indentation, in columns.
  51.     """
  52.     return ((cols / TAB_WIDTH) * '\t') + ((cols % TAB_WIDTH) * ' ')
  53.  
  54.  
  55. def pprint(seq, stream = None, indent = 0, allowance = 0):
  56.     """Pretty-print a list, tuple, or dictionary.
  57.  
  58.     seq
  59.     List, tuple, or dictionary object to be pretty-printed.  Other
  60.     object types are permitted by are not specially interpreted.
  61.  
  62.     stream
  63.     Output stream.  If not provided, `sys.stdout' is used.  This
  64.     parameter must support the `write()' method with a single
  65.     parameter, which will always be a string.  It may be a
  66.     `StringIO.StringIO' object if the result is needed as a
  67.     string.
  68.  
  69.     Indentation is done according to `INDENT_PER_LEVEL', which may be
  70.     set to any non-negative integer before calling this function.  The
  71.     output written on the stream is a perfectly valid representation
  72.     of the Python object passed in, with indentation to assist
  73.     human-readable interpretation.  The output can be used as input
  74.     without error, given readable representations of all elements are
  75.     available via `repr()'.  Output is restricted to `MAX_WIDTH'
  76.     columns where possible.
  77.     """
  78.     if stream is None:
  79.     import sys
  80.     stream = sys.stdout
  81.  
  82.     rep = `seq`
  83.     typ = type(seq)
  84.     sepLines = len(rep) > (MAX_WIDTH - 1 - indent - allowance)
  85.  
  86.     if sepLines and (typ is ListType or typ is TupleType):
  87.     #  Pretty-print the sequence.
  88.     stream.write(((typ is ListType) and '[') or '(')
  89.  
  90.     length = len(seq)
  91.     if length:
  92.         indent = indent + INDENT_PER_LEVEL
  93.         pprint(seq[0], stream, indent, allowance + 1)
  94.  
  95.         if len(seq) > 1:
  96.         for ent in seq[1:]:
  97.             stream.write(',\n' + _indentation(indent))
  98.             pprint(ent, stream, indent, allowance + 1)
  99.  
  100.         indent = indent - INDENT_PER_LEVEL
  101.  
  102.     stream.write(((typ is ListType) and ']') or ')')
  103.  
  104.     elif typ is DictType and sepLines:
  105.     stream.write('{')
  106.  
  107.     length = len(seq)
  108.     if length:
  109.         indent = indent + INDENT_PER_LEVEL
  110.         items  = seq.items()
  111.         items.sort()
  112.         key, ent = items[0]
  113.         rep = `key` + ': '
  114.         stream.write(rep)
  115.         pprint(ent, stream, indent + len(rep), allowance + 1)
  116.  
  117.         if len(items) > 1:
  118.         for key, ent in items[1:]:
  119.             rep = `key` + ': '
  120.             stream.write(',\n' + _indentation(indent) + rep)
  121.             pprint(ent, stream, indent + len(rep), allowance + 1)
  122.  
  123.         indent = indent - INDENT_PER_LEVEL
  124.  
  125.     stream.write('}')
  126.  
  127.     else:
  128.     stream.write(rep)
  129.  
  130.     #  Terminate the 'print' if we're not a recursive invocation.
  131.     if not indent:
  132.     stream.write('\n')
  133.  
  134.  
  135. #
  136. #  end of file
  137.