reprlib.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """Redo the builtin repr() (representation) but with limits on most sizes."""
  2. __all__ = ["Repr", "repr", "recursive_repr"]
  3. import builtins
  4. from itertools import islice
  5. from _thread import get_ident
  6. def recursive_repr(fillvalue='...'):
  7. 'Decorator to make a repr function return fillvalue for a recursive call'
  8. def decorating_function(user_function):
  9. repr_running = set()
  10. def wrapper(self):
  11. key = id(self), get_ident()
  12. if key in repr_running:
  13. return fillvalue
  14. repr_running.add(key)
  15. try:
  16. result = user_function(self)
  17. finally:
  18. repr_running.discard(key)
  19. return result
  20. # Can't use functools.wraps() here because of bootstrap issues
  21. wrapper.__module__ = getattr(user_function, '__module__')
  22. wrapper.__doc__ = getattr(user_function, '__doc__')
  23. wrapper.__name__ = getattr(user_function, '__name__')
  24. wrapper.__qualname__ = getattr(user_function, '__qualname__')
  25. wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
  26. return wrapper
  27. return decorating_function
  28. class Repr:
  29. def __init__(self):
  30. self.maxlevel = 6
  31. self.maxtuple = 6
  32. self.maxlist = 6
  33. self.maxarray = 5
  34. self.maxdict = 4
  35. self.maxset = 6
  36. self.maxfrozenset = 6
  37. self.maxdeque = 6
  38. self.maxstring = 30
  39. self.maxlong = 40
  40. self.maxother = 30
  41. def repr(self, x):
  42. return self.repr1(x, self.maxlevel)
  43. def repr1(self, x, level):
  44. typename = type(x).__name__
  45. if ' ' in typename:
  46. parts = typename.split()
  47. typename = '_'.join(parts)
  48. if hasattr(self, 'repr_' + typename):
  49. return getattr(self, 'repr_' + typename)(x, level)
  50. else:
  51. return self.repr_instance(x, level)
  52. def _repr_iterable(self, x, level, left, right, maxiter, trail=''):
  53. n = len(x)
  54. if level <= 0 and n:
  55. s = '...'
  56. else:
  57. newlevel = level - 1
  58. repr1 = self.repr1
  59. pieces = [repr1(elem, newlevel) for elem in islice(x, maxiter)]
  60. if n > maxiter: pieces.append('...')
  61. s = ', '.join(pieces)
  62. if n == 1 and trail: right = trail + right
  63. return '%s%s%s' % (left, s, right)
  64. def repr_tuple(self, x, level):
  65. return self._repr_iterable(x, level, '(', ')', self.maxtuple, ',')
  66. def repr_list(self, x, level):
  67. return self._repr_iterable(x, level, '[', ']', self.maxlist)
  68. def repr_array(self, x, level):
  69. if not x:
  70. return "array('%s')" % x.typecode
  71. header = "array('%s', [" % x.typecode
  72. return self._repr_iterable(x, level, header, '])', self.maxarray)
  73. def repr_set(self, x, level):
  74. if not x:
  75. return 'set()'
  76. x = _possibly_sorted(x)
  77. return self._repr_iterable(x, level, '{', '}', self.maxset)
  78. def repr_frozenset(self, x, level):
  79. if not x:
  80. return 'frozenset()'
  81. x = _possibly_sorted(x)
  82. return self._repr_iterable(x, level, 'frozenset({', '})',
  83. self.maxfrozenset)
  84. def repr_deque(self, x, level):
  85. return self._repr_iterable(x, level, 'deque([', '])', self.maxdeque)
  86. def repr_dict(self, x, level):
  87. n = len(x)
  88. if n == 0: return '{}'
  89. if level <= 0: return '{...}'
  90. newlevel = level - 1
  91. repr1 = self.repr1
  92. pieces = []
  93. for key in islice(_possibly_sorted(x), self.maxdict):
  94. keyrepr = repr1(key, newlevel)
  95. valrepr = repr1(x[key], newlevel)
  96. pieces.append('%s: %s' % (keyrepr, valrepr))
  97. if n > self.maxdict: pieces.append('...')
  98. s = ', '.join(pieces)
  99. return '{%s}' % (s,)
  100. def repr_str(self, x, level):
  101. s = builtins.repr(x[:self.maxstring])
  102. if len(s) > self.maxstring:
  103. i = max(0, (self.maxstring-3)//2)
  104. j = max(0, self.maxstring-3-i)
  105. s = builtins.repr(x[:i] + x[len(x)-j:])
  106. s = s[:i] + '...' + s[len(s)-j:]
  107. return s
  108. def repr_int(self, x, level):
  109. s = builtins.repr(x) # XXX Hope this isn't too slow...
  110. if len(s) > self.maxlong:
  111. i = max(0, (self.maxlong-3)//2)
  112. j = max(0, self.maxlong-3-i)
  113. s = s[:i] + '...' + s[len(s)-j:]
  114. return s
  115. def repr_instance(self, x, level):
  116. try:
  117. s = builtins.repr(x)
  118. # Bugs in x.__repr__() can cause arbitrary
  119. # exceptions -- then make up something
  120. except Exception:
  121. return '<%s instance at %#x>' % (x.__class__.__name__, id(x))
  122. if len(s) > self.maxother:
  123. i = max(0, (self.maxother-3)//2)
  124. j = max(0, self.maxother-3-i)
  125. s = s[:i] + '...' + s[len(s)-j:]
  126. return s
  127. def _possibly_sorted(x):
  128. # Since not all sequences of items can be sorted and comparison
  129. # functions may raise arbitrary exceptions, return an unsorted
  130. # sequence in that case.
  131. try:
  132. return sorted(x)
  133. except Exception:
  134. return list(x)
  135. aRepr = Repr()
  136. repr = aRepr.repr