home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1786 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  17.1 KB  |  542 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import __future__
  5. import sys
  6. import types
  7. import re
  8. import datetime
  9. from StringIO import StringIO
  10. from collections import deque
  11. __all__ = [
  12.     'pretty',
  13.     'pprint',
  14.     'PrettyPrinter',
  15.     'RepresentationPrinter',
  16.     'for_type',
  17.     'for_type_by_name']
  18. _re_pattern_type = type(re.compile(''))
  19.  
  20. def pretty(obj, verbose = False, max_width = 79, newline = '\n'):
  21.     stream = StringIO()
  22.     printer = RepresentationPrinter(stream, verbose, max_width, newline)
  23.     printer.pretty(obj)
  24.     printer.flush()
  25.     return stream.getvalue()
  26.  
  27.  
  28. def pprint(obj, verbose = False, max_width = 79, newline = '\n'):
  29.     printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)
  30.     printer.pretty(obj)
  31.     printer.flush()
  32.     sys.stdout.write(newline)
  33.     sys.stdout.flush()
  34.  
  35. if hasattr(__future__, 'with_statement'):
  36.     exec '\nfrom __future__ import with_statement\nfrom contextlib import contextmanager\n\nclass _PrettyPrinterBase(object):\n\n    @contextmanager\n    def indent(self, indent):\n        """with statement support for indenting/dedenting."""\n        self.indentation += indent\n        try:\n            yield\n        finally:\n            self.indentation -= indent\n\n    @contextmanager\n    def group(self, indent=0, open=\'\', close=\'\'):\n        """like begin_group / end_group but for the with statement."""\n        self.begin_group(indent, open)\n        try:\n            with self.indent(indent):\n                yield\n        finally:\n            self.end_group(indent, close)\n'
  37. else:
  38.     
  39.     class _PrettyPrinterBase(object):
  40.         
  41.         def _unsupported(self, *a, **kw):
  42.             raise RuntimeError('not available in this python version')
  43.  
  44.         group = indent = _unsupported
  45.         del _unsupported
  46.  
  47.  
  48. class PrettyPrinter(_PrettyPrinterBase):
  49.     
  50.     def __init__(self, output, max_width = 79, newline = '\n'):
  51.         self.output = output
  52.         self.max_width = max_width
  53.         self.newline = newline
  54.         self.output_width = 0
  55.         self.buffer_width = 0
  56.         self.buffer = deque()
  57.         root_group = Group(0)
  58.         self.group_stack = [
  59.             root_group]
  60.         self.group_queue = GroupQueue(root_group)
  61.         self.indentation = 0
  62.  
  63.     
  64.     def _break_outer_groups(self):
  65.         while self.max_width < self.output_width + self.buffer_width:
  66.             group = self.group_queue.deq()
  67.             if not group:
  68.                 return None
  69.             while group.breakables:
  70.                 x = self.buffer.popleft()
  71.                 self.output_width = x.output(self.output, self.output_width)
  72.                 self.buffer_width -= x.width
  73.                 continue
  74.                 self
  75.             while self.buffer and isinstance(self.buffer[0], Text):
  76.                 x = self.buffer.popleft()
  77.                 self.output_width = x.output(self.output, self.output_width)
  78.                 self.buffer_width -= x.width
  79.                 continue
  80.                 self
  81.             continue
  82.             group
  83.  
  84.     
  85.     def text(self, obj):
  86.         width = len(obj)
  87.  
  88.     
  89.     def breakable(self, sep = ' '):
  90.         width = len(sep)
  91.         group = self.group_stack[-1]
  92.  
  93.     
  94.     def begin_group(self, indent = 0, open = ''):
  95.         if open:
  96.             self.text(open)
  97.         
  98.         group = Group(self.group_stack[-1].depth + 1)
  99.         self.group_stack.append(group)
  100.         self.group_queue.enq(group)
  101.         self.indentation += indent
  102.  
  103.     
  104.     def end_group(self, dedent = 0, close = ''):
  105.         self.indentation -= dedent
  106.         group = self.group_stack.pop()
  107.         if not group.breakables:
  108.             self.group_queue.remove(group)
  109.         
  110.         if close:
  111.             self.text(close)
  112.         
  113.  
  114.     
  115.     def flush(self):
  116.         for data in self.buffer:
  117.             self.output_width += data.output(self.output, self.output_width)
  118.         
  119.         self.buffer.clear()
  120.         self.buffer_width = 0
  121.  
  122.  
  123.  
  124. def _get_mro(obj_class):
  125.     if not hasattr(obj_class, '__mro__'):
  126.         
  127.         try:
  128.             obj_class = type(obj_class.__name__, (obj_class, object), { })
  129.         except TypeError:
  130.             mro = [
  131.                 obj_class]
  132.  
  133.         mro = obj_class.__mro__[1:-1]
  134.     else:
  135.         mro = obj_class.__mro__
  136.     return mro
  137.  
  138.  
  139. class RepresentationPrinter(PrettyPrinter):
  140.     
  141.     def __init__(self, output, verbose = False, max_width = 79, newline = '\n'):
  142.         PrettyPrinter.__init__(self, output, max_width, newline)
  143.         self.verbose = verbose
  144.         self.stack = []
  145.  
  146.     
  147.     def pretty(self, obj):
  148.         obj_id = id(obj)
  149.         cycle = obj_id in self.stack
  150.         self.stack.append(obj_id)
  151.         self.begin_group()
  152.         
  153.         try:
  154.             if not getattr(obj, '__class__', None):
  155.                 pass
  156.             obj_class = type(obj)
  157.             if hasattr(obj_class, '__pretty__'):
  158.                 return obj_class.__pretty__(obj, self, cycle)
  159.             
  160.             try:
  161.                 printer = _singleton_pprinters[obj_id]
  162.             except (TypeError, KeyError):
  163.                 hasattr(obj_class, '__pretty__')
  164.                 hasattr(obj_class, '__pretty__')
  165.             except:
  166.                 hasattr(obj_class, '__pretty__')
  167.  
  168.             return printer(obj, self, cycle)
  169.             for cls in _get_mro(obj_class):
  170.                 if cls in _type_pprinters:
  171.                     return _type_pprinters[cls](obj, self, cycle)
  172.                 printer = self._in_deferred_types(cls)
  173.                 if printer is not None:
  174.                     return printer(obj, self, cycle)
  175.             
  176.             return _default_pprint(obj, self, cycle)
  177.         finally:
  178.             self.end_group()
  179.             self.stack.pop()
  180.  
  181.  
  182.     
  183.     def _in_deferred_types(self, cls):
  184.         mod = getattr(cls, '__module__', None)
  185.         name = getattr(cls, '__name__', None)
  186.         key = (mod, name)
  187.         printer = None
  188.         if key in _deferred_type_pprinters:
  189.             printer = _deferred_type_pprinters.pop(key)
  190.             _type_pprinters[cls] = printer
  191.         
  192.         return printer
  193.  
  194.  
  195.  
  196. class Printable(object):
  197.     
  198.     def output(self, stream, output_width):
  199.         return output_width
  200.  
  201.  
  202.  
  203. class Text(Printable):
  204.     
  205.     def __init__(self):
  206.         self.objs = []
  207.         self.width = 0
  208.  
  209.     
  210.     def output(self, stream, output_width):
  211.         for obj in self.objs:
  212.             stream.write(obj)
  213.         
  214.         return output_width + self.width
  215.  
  216.     
  217.     def add(self, obj, width):
  218.         self.objs.append(obj)
  219.         self.width += width
  220.  
  221.  
  222.  
  223. class Breakable(Printable):
  224.     
  225.     def __init__(self, seq, width, pretty):
  226.         self.obj = seq
  227.         self.width = width
  228.         self.pretty = pretty
  229.         self.indentation = pretty.indentation
  230.         self.group = pretty.group_stack[-1]
  231.         self.group.breakables.append(self)
  232.  
  233.     
  234.     def output(self, stream, output_width):
  235.         self.group.breakables.popleft()
  236.         if self.group.want_break:
  237.             stream.write(self.pretty.newline)
  238.             stream.write(' ' * self.indentation)
  239.             return self.indentation
  240.         if not self.group.breakables:
  241.             self.pretty.group_queue.remove(self.group)
  242.         
  243.         stream.write(self.obj)
  244.         return output_width + self.width
  245.  
  246.  
  247.  
  248. class Group(Printable):
  249.     
  250.     def __init__(self, depth):
  251.         self.depth = depth
  252.         self.breakables = deque()
  253.         self.want_break = False
  254.  
  255.  
  256.  
  257. class GroupQueue(object):
  258.     
  259.     def __init__(self, *groups):
  260.         self.queue = []
  261.         for group in groups:
  262.             self.enq(group)
  263.         
  264.  
  265.     
  266.     def enq(self, group):
  267.         depth = group.depth
  268.         while depth > len(self.queue) - 1:
  269.             self.queue.append([])
  270.         self.queue[depth].append(group)
  271.  
  272.     
  273.     def deq(self):
  274.         for stack in self.queue:
  275.             for idx, group in enumerate(reversed(stack)):
  276.                 if group.breakables:
  277.                     del stack[idx]
  278.                     group.want_break = True
  279.                     return group
  280.             
  281.             for group in stack:
  282.                 group.want_break = True
  283.             
  284.             del stack[:]
  285.         
  286.  
  287.     
  288.     def remove(self, group):
  289.         
  290.         try:
  291.             self.queue[group.depth].remove(group)
  292.         except ValueError:
  293.             pass
  294.  
  295.  
  296.  
  297. _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
  298.  
  299. def _default_pprint(obj, p, cycle):
  300.     if not getattr(obj, '__class__', None):
  301.         pass
  302.     klass = type(obj)
  303.     if getattr(klass, '__repr__', None) not in _baseclass_reprs:
  304.         p.text(repr(obj))
  305.         return None
  306.     p.begin_group(1, '<')
  307.     p.pretty(klass)
  308.     p.text(' at 0x%x' % id(obj))
  309.     if cycle:
  310.         p.text(' ...')
  311.     elif p.verbose:
  312.         first = True
  313.         for key in dir(obj):
  314.             if not key.startswith('_'):
  315.                 
  316.                 try:
  317.                     value = getattr(obj, key)
  318.                 except AttributeError:
  319.                     continue
  320.  
  321.                 if isinstance(value, types.MethodType):
  322.                     continue
  323.                 
  324.                 if not first:
  325.                     p.text(',')
  326.                 
  327.                 p.breakable()
  328.                 p.text(key)
  329.                 p.text('=')
  330.                 step = len(key) + 1
  331.                 p.indentation += step
  332.                 p.pretty(value)
  333.                 p.indentation -= step
  334.                 first = False
  335.                 continue
  336.             p
  337.         
  338.     
  339.     p.end_group(1, '>')
  340.  
  341.  
  342. def _seq_pprinter_factory(start, end):
  343.     
  344.     def inner(obj, p, cycle):
  345.         if cycle:
  346.             return p.text(start + '...' + end)
  347.         step = len(start)
  348.         p.begin_group(step, start)
  349.         for idx, x in enumerate(obj):
  350.             if idx:
  351.                 p.text(',')
  352.                 p.breakable()
  353.             
  354.             p.pretty(x)
  355.         
  356.         if len(obj) == 1 and type(obj) is tuple:
  357.             p.text(',')
  358.         
  359.         p.end_group(step, end)
  360.  
  361.     return inner
  362.  
  363.  
  364. def _dict_pprinter_factory(start, end):
  365.     
  366.     def inner(obj, p, cycle):
  367.         if cycle:
  368.             return p.text('{...}')
  369.         p.begin_group(1, start)
  370.         keys = obj.keys()
  371.         
  372.         try:
  373.             keys.sort()
  374.         except Exception:
  375.             cycle
  376.             e = cycle
  377.         except:
  378.             cycle
  379.  
  380.         for idx, key in enumerate(keys):
  381.             if idx:
  382.                 p.text(',')
  383.                 p.breakable()
  384.             
  385.             p.pretty(key)
  386.             p.text(': ')
  387.             p.pretty(obj[key])
  388.         
  389.         p.end_group(1, end)
  390.  
  391.     return inner
  392.  
  393.  
  394. def _super_pprint(obj, p, cycle):
  395.     p.begin_group(8, '<super: ')
  396.     p.pretty(obj.__self_class__)
  397.     p.text(',')
  398.     p.breakable()
  399.     p.pretty(obj.__self__)
  400.     p.end_group(8, '>')
  401.  
  402.  
  403. def _re_pattern_pprint(obj, p, cycle):
  404.     p.text('re.compile(')
  405.     pattern = repr(obj.pattern)
  406.     if pattern[:1] in 'uU':
  407.         pattern = pattern[1:]
  408.         prefix = 'ur'
  409.     else:
  410.         prefix = 'r'
  411.     pattern = prefix + pattern.replace('\\\\', '\\')
  412.     p.text(pattern)
  413.     if obj.flags:
  414.         p.text(',')
  415.         p.breakable()
  416.         done_one = False
  417.         for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'UNICODE', 'VERBOSE', 'DEBUG'):
  418.             if obj.flags & getattr(re, flag):
  419.                 if done_one:
  420.                     p.text('|')
  421.                 
  422.                 p.text('re.' + flag)
  423.                 done_one = True
  424.                 continue
  425.         
  426.     
  427.     p.text(')')
  428.  
  429.  
  430. def _type_pprint(obj, p, cycle):
  431.     if obj.__module__ in ('__builtin__', 'exceptions'):
  432.         name = obj.__name__
  433.     else:
  434.         name = obj.__module__ + '.' + obj.__name__
  435.     p.text(name)
  436.  
  437.  
  438. def _repr_pprint(obj, p, cycle):
  439.     p.text(repr(obj))
  440.  
  441.  
  442. def _function_pprint(obj, p, cycle):
  443.     if obj.__module__ in ('__builtin__', 'exceptions') or not (obj.__module__):
  444.         name = obj.__name__
  445.     else:
  446.         name = obj.__module__ + '.' + obj.__name__
  447.     p.text('<function %s>' % name)
  448.  
  449.  
  450. def _exception_pprint(obj, p, cycle):
  451.     if obj.__class__.__module__ == 'exceptions':
  452.         name = obj.__class__.__name__
  453.     else:
  454.         name = '%s.%s' % (obj.__class__.__module__, obj.__class__.__name__)
  455.     step = len(name) + 1
  456.     p.begin_group(step, '(')
  457.     for idx, arg in enumerate(getattr(obj, 'args', ())):
  458.         if idx:
  459.             p.text(',')
  460.             p.breakable()
  461.         
  462.         p.pretty(arg)
  463.     
  464.     p.end_group(step, ')')
  465.  
  466.  
  467. try:
  468.     _exception_base = BaseException
  469. except NameError:
  470.     _exception_base = Exception
  471.  
  472. _type_pprinters = {
  473.     int: _repr_pprint,
  474.     long: _repr_pprint,
  475.     float: _repr_pprint,
  476.     str: _repr_pprint,
  477.     unicode: _repr_pprint,
  478.     tuple: _seq_pprinter_factory('(', ')'),
  479.     list: _seq_pprinter_factory('[', ']'),
  480.     dict: _dict_pprinter_factory('{', '}'),
  481.     types.DictProxyType: _dict_pprinter_factory('<dictproxy {', '}>'),
  482.     set: _seq_pprinter_factory('set([', '])'),
  483.     frozenset: _seq_pprinter_factory('frozenset([', '])'),
  484.     super: _super_pprint,
  485.     _re_pattern_type: _re_pattern_pprint,
  486.     type: _type_pprint,
  487.     types.ClassType: _type_pprint,
  488.     types.FunctionType: _function_pprint,
  489.     types.BuiltinFunctionType: _function_pprint,
  490.     types.SliceType: _repr_pprint,
  491.     types.MethodType: _repr_pprint,
  492.     xrange: _repr_pprint,
  493.     datetime.datetime: _repr_pprint,
  494.     datetime.timedelta: _repr_pprint,
  495.     _exception_base: _exception_pprint }
  496. _deferred_type_pprinters = { }
  497.  
  498. def for_type(typ, func):
  499.     oldfunc = _type_pprinters.get(typ, None)
  500.     if func is not None:
  501.         _type_pprinters[typ] = func
  502.     
  503.     return oldfunc
  504.  
  505.  
  506. def for_type_by_name(type_module, type_name, func):
  507.     key = (type_module, type_name)
  508.     oldfunc = _deferred_type_pprinters.get(key, None)
  509.     if func is not None:
  510.         _deferred_type_pprinters[key] = func
  511.     
  512.     return oldfunc
  513.  
  514. _singleton_pprinters = dict.fromkeys(map(id, [
  515.     None,
  516.     True,
  517.     False,
  518.     Ellipsis,
  519.     NotImplemented]), _repr_pprint)
  520. if __name__ == '__main__':
  521.     from random import randrange
  522.     
  523.     class Foo(object):
  524.         
  525.         def __init__(self):
  526.             self.foo = 1
  527.             self.bar = re.compile('\\s+')
  528.             self.blub = dict.fromkeys(range(30), randrange(1, 40))
  529.             self.hehe = 23424.2
  530.             self.list = [
  531.                 'blub',
  532.                 'blah',
  533.                 self]
  534.  
  535.         
  536.         def get_foo(self):
  537.             print 'foo'
  538.  
  539.  
  540.     pprint(Foo(), verbose = True)
  541.  
  542.