home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.6)
-
- import __future__
- import sys
- import types
- import re
- import datetime
- from StringIO import StringIO
- from collections import deque
- __all__ = [
- 'pretty',
- 'pprint',
- 'PrettyPrinter',
- 'RepresentationPrinter',
- 'for_type',
- 'for_type_by_name']
- _re_pattern_type = type(re.compile(''))
-
- def pretty(obj, verbose = False, max_width = 79, newline = '\n'):
- stream = StringIO()
- printer = RepresentationPrinter(stream, verbose, max_width, newline)
- printer.pretty(obj)
- printer.flush()
- return stream.getvalue()
-
-
- def pprint(obj, verbose = False, max_width = 79, newline = '\n'):
- printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)
- printer.pretty(obj)
- printer.flush()
- sys.stdout.write(newline)
- sys.stdout.flush()
-
- if hasattr(__future__, 'with_statement'):
- 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'
- else:
-
- class _PrettyPrinterBase(object):
-
- def _unsupported(self, *a, **kw):
- raise RuntimeError('not available in this python version')
-
- group = indent = _unsupported
- del _unsupported
-
-
- class PrettyPrinter(_PrettyPrinterBase):
-
- def __init__(self, output, max_width = 79, newline = '\n'):
- self.output = output
- self.max_width = max_width
- self.newline = newline
- self.output_width = 0
- self.buffer_width = 0
- self.buffer = deque()
- root_group = Group(0)
- self.group_stack = [
- root_group]
- self.group_queue = GroupQueue(root_group)
- self.indentation = 0
-
-
- def _break_outer_groups(self):
- while self.max_width < self.output_width + self.buffer_width:
- group = self.group_queue.deq()
- if not group:
- return None
- while group.breakables:
- x = self.buffer.popleft()
- self.output_width = x.output(self.output, self.output_width)
- self.buffer_width -= x.width
- continue
- self
- while self.buffer and isinstance(self.buffer[0], Text):
- x = self.buffer.popleft()
- self.output_width = x.output(self.output, self.output_width)
- self.buffer_width -= x.width
- continue
- self
- continue
- group
-
-
- def text(self, obj):
- width = len(obj)
-
-
- def breakable(self, sep = ' '):
- width = len(sep)
- group = self.group_stack[-1]
-
-
- def begin_group(self, indent = 0, open = ''):
- if open:
- self.text(open)
-
- group = Group(self.group_stack[-1].depth + 1)
- self.group_stack.append(group)
- self.group_queue.enq(group)
- self.indentation += indent
-
-
- def end_group(self, dedent = 0, close = ''):
- self.indentation -= dedent
- group = self.group_stack.pop()
- if not group.breakables:
- self.group_queue.remove(group)
-
- if close:
- self.text(close)
-
-
-
- def flush(self):
- for data in self.buffer:
- self.output_width += data.output(self.output, self.output_width)
-
- self.buffer.clear()
- self.buffer_width = 0
-
-
-
- def _get_mro(obj_class):
- if not hasattr(obj_class, '__mro__'):
-
- try:
- obj_class = type(obj_class.__name__, (obj_class, object), { })
- except TypeError:
- mro = [
- obj_class]
-
- mro = obj_class.__mro__[1:-1]
- else:
- mro = obj_class.__mro__
- return mro
-
-
- class RepresentationPrinter(PrettyPrinter):
-
- def __init__(self, output, verbose = False, max_width = 79, newline = '\n'):
- PrettyPrinter.__init__(self, output, max_width, newline)
- self.verbose = verbose
- self.stack = []
-
-
- def pretty(self, obj):
- obj_id = id(obj)
- cycle = obj_id in self.stack
- self.stack.append(obj_id)
- self.begin_group()
-
- try:
- if not getattr(obj, '__class__', None):
- pass
- obj_class = type(obj)
- if hasattr(obj_class, '__pretty__'):
- return obj_class.__pretty__(obj, self, cycle)
-
- try:
- printer = _singleton_pprinters[obj_id]
- except (TypeError, KeyError):
- hasattr(obj_class, '__pretty__')
- hasattr(obj_class, '__pretty__')
- except:
- hasattr(obj_class, '__pretty__')
-
- return printer(obj, self, cycle)
- for cls in _get_mro(obj_class):
- if cls in _type_pprinters:
- return _type_pprinters[cls](obj, self, cycle)
- printer = self._in_deferred_types(cls)
- if printer is not None:
- return printer(obj, self, cycle)
-
- return _default_pprint(obj, self, cycle)
- finally:
- self.end_group()
- self.stack.pop()
-
-
-
- def _in_deferred_types(self, cls):
- mod = getattr(cls, '__module__', None)
- name = getattr(cls, '__name__', None)
- key = (mod, name)
- printer = None
- if key in _deferred_type_pprinters:
- printer = _deferred_type_pprinters.pop(key)
- _type_pprinters[cls] = printer
-
- return printer
-
-
-
- class Printable(object):
-
- def output(self, stream, output_width):
- return output_width
-
-
-
- class Text(Printable):
-
- def __init__(self):
- self.objs = []
- self.width = 0
-
-
- def output(self, stream, output_width):
- for obj in self.objs:
- stream.write(obj)
-
- return output_width + self.width
-
-
- def add(self, obj, width):
- self.objs.append(obj)
- self.width += width
-
-
-
- class Breakable(Printable):
-
- def __init__(self, seq, width, pretty):
- self.obj = seq
- self.width = width
- self.pretty = pretty
- self.indentation = pretty.indentation
- self.group = pretty.group_stack[-1]
- self.group.breakables.append(self)
-
-
- def output(self, stream, output_width):
- self.group.breakables.popleft()
- if self.group.want_break:
- stream.write(self.pretty.newline)
- stream.write(' ' * self.indentation)
- return self.indentation
- if not self.group.breakables:
- self.pretty.group_queue.remove(self.group)
-
- stream.write(self.obj)
- return output_width + self.width
-
-
-
- class Group(Printable):
-
- def __init__(self, depth):
- self.depth = depth
- self.breakables = deque()
- self.want_break = False
-
-
-
- class GroupQueue(object):
-
- def __init__(self, *groups):
- self.queue = []
- for group in groups:
- self.enq(group)
-
-
-
- def enq(self, group):
- depth = group.depth
- while depth > len(self.queue) - 1:
- self.queue.append([])
- self.queue[depth].append(group)
-
-
- def deq(self):
- for stack in self.queue:
- for idx, group in enumerate(reversed(stack)):
- if group.breakables:
- del stack[idx]
- group.want_break = True
- return group
-
- for group in stack:
- group.want_break = True
-
- del stack[:]
-
-
-
- def remove(self, group):
-
- try:
- self.queue[group.depth].remove(group)
- except ValueError:
- pass
-
-
-
- _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
-
- def _default_pprint(obj, p, cycle):
- if not getattr(obj, '__class__', None):
- pass
- klass = type(obj)
- if getattr(klass, '__repr__', None) not in _baseclass_reprs:
- p.text(repr(obj))
- return None
- p.begin_group(1, '<')
- p.pretty(klass)
- p.text(' at 0x%x' % id(obj))
- if cycle:
- p.text(' ...')
- elif p.verbose:
- first = True
- for key in dir(obj):
- if not key.startswith('_'):
-
- try:
- value = getattr(obj, key)
- except AttributeError:
- continue
-
- if isinstance(value, types.MethodType):
- continue
-
- if not first:
- p.text(',')
-
- p.breakable()
- p.text(key)
- p.text('=')
- step = len(key) + 1
- p.indentation += step
- p.pretty(value)
- p.indentation -= step
- first = False
- continue
- p
-
-
- p.end_group(1, '>')
-
-
- def _seq_pprinter_factory(start, end):
-
- def inner(obj, p, cycle):
- if cycle:
- return p.text(start + '...' + end)
- step = len(start)
- p.begin_group(step, start)
- for idx, x in enumerate(obj):
- if idx:
- p.text(',')
- p.breakable()
-
- p.pretty(x)
-
- if len(obj) == 1 and type(obj) is tuple:
- p.text(',')
-
- p.end_group(step, end)
-
- return inner
-
-
- def _dict_pprinter_factory(start, end):
-
- def inner(obj, p, cycle):
- if cycle:
- return p.text('{...}')
- p.begin_group(1, start)
- keys = obj.keys()
-
- try:
- keys.sort()
- except Exception:
- cycle
- e = cycle
- except:
- cycle
-
- for idx, key in enumerate(keys):
- if idx:
- p.text(',')
- p.breakable()
-
- p.pretty(key)
- p.text(': ')
- p.pretty(obj[key])
-
- p.end_group(1, end)
-
- return inner
-
-
- def _super_pprint(obj, p, cycle):
- p.begin_group(8, '<super: ')
- p.pretty(obj.__self_class__)
- p.text(',')
- p.breakable()
- p.pretty(obj.__self__)
- p.end_group(8, '>')
-
-
- def _re_pattern_pprint(obj, p, cycle):
- p.text('re.compile(')
- pattern = repr(obj.pattern)
- if pattern[:1] in 'uU':
- pattern = pattern[1:]
- prefix = 'ur'
- else:
- prefix = 'r'
- pattern = prefix + pattern.replace('\\\\', '\\')
- p.text(pattern)
- if obj.flags:
- p.text(',')
- p.breakable()
- done_one = False
- for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'UNICODE', 'VERBOSE', 'DEBUG'):
- if obj.flags & getattr(re, flag):
- if done_one:
- p.text('|')
-
- p.text('re.' + flag)
- done_one = True
- continue
-
-
- p.text(')')
-
-
- def _type_pprint(obj, p, cycle):
- if obj.__module__ in ('__builtin__', 'exceptions'):
- name = obj.__name__
- else:
- name = obj.__module__ + '.' + obj.__name__
- p.text(name)
-
-
- def _repr_pprint(obj, p, cycle):
- p.text(repr(obj))
-
-
- def _function_pprint(obj, p, cycle):
- if obj.__module__ in ('__builtin__', 'exceptions') or not (obj.__module__):
- name = obj.__name__
- else:
- name = obj.__module__ + '.' + obj.__name__
- p.text('<function %s>' % name)
-
-
- def _exception_pprint(obj, p, cycle):
- if obj.__class__.__module__ == 'exceptions':
- name = obj.__class__.__name__
- else:
- name = '%s.%s' % (obj.__class__.__module__, obj.__class__.__name__)
- step = len(name) + 1
- p.begin_group(step, '(')
- for idx, arg in enumerate(getattr(obj, 'args', ())):
- if idx:
- p.text(',')
- p.breakable()
-
- p.pretty(arg)
-
- p.end_group(step, ')')
-
-
- try:
- _exception_base = BaseException
- except NameError:
- _exception_base = Exception
-
- _type_pprinters = {
- int: _repr_pprint,
- long: _repr_pprint,
- float: _repr_pprint,
- str: _repr_pprint,
- unicode: _repr_pprint,
- tuple: _seq_pprinter_factory('(', ')'),
- list: _seq_pprinter_factory('[', ']'),
- dict: _dict_pprinter_factory('{', '}'),
- types.DictProxyType: _dict_pprinter_factory('<dictproxy {', '}>'),
- set: _seq_pprinter_factory('set([', '])'),
- frozenset: _seq_pprinter_factory('frozenset([', '])'),
- super: _super_pprint,
- _re_pattern_type: _re_pattern_pprint,
- type: _type_pprint,
- types.ClassType: _type_pprint,
- types.FunctionType: _function_pprint,
- types.BuiltinFunctionType: _function_pprint,
- types.SliceType: _repr_pprint,
- types.MethodType: _repr_pprint,
- xrange: _repr_pprint,
- datetime.datetime: _repr_pprint,
- datetime.timedelta: _repr_pprint,
- _exception_base: _exception_pprint }
- _deferred_type_pprinters = { }
-
- def for_type(typ, func):
- oldfunc = _type_pprinters.get(typ, None)
- if func is not None:
- _type_pprinters[typ] = func
-
- return oldfunc
-
-
- def for_type_by_name(type_module, type_name, func):
- key = (type_module, type_name)
- oldfunc = _deferred_type_pprinters.get(key, None)
- if func is not None:
- _deferred_type_pprinters[key] = func
-
- return oldfunc
-
- _singleton_pprinters = dict.fromkeys(map(id, [
- None,
- True,
- False,
- Ellipsis,
- NotImplemented]), _repr_pprint)
- if __name__ == '__main__':
- from random import randrange
-
- class Foo(object):
-
- def __init__(self):
- self.foo = 1
- self.bar = re.compile('\\s+')
- self.blub = dict.fromkeys(range(30), randrange(1, 40))
- self.hehe = 23424.2
- self.list = [
- 'blub',
- 'blah',
- self]
-
-
- def get_foo(self):
- print 'foo'
-
-
- pprint(Foo(), verbose = True)
-
-