reprlib.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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__(
  30. self, *, maxlevel=6, maxtuple=6, maxlist=6, maxarray=5, maxdict=4,
  31. maxset=6, maxfrozenset=6, maxdeque=6, maxstring=30, maxlong=40,
  32. maxother=30, fillvalue='...', indent=None,
  33. ):
  34. self.maxlevel = maxlevel
  35. self.maxtuple = maxtuple
  36. self.maxlist = maxlist
  37. self.maxarray = maxarray
  38. self.maxdict = maxdict
  39. self.maxset = maxset
  40. self.maxfrozenset = maxfrozenset
  41. self.maxdeque = maxdeque
  42. self.maxstring = maxstring
  43. self.maxlong = maxlong
  44. self.maxother = maxother
  45. self.fillvalue = fillvalue
  46. self.indent = indent
  47. def repr(self, x):
  48. return self.repr1(x, self.maxlevel)
  49. def repr1(self, x, level):
  50. typename = type(x).__name__
  51. if ' ' in typename:
  52. parts = typename.split()
  53. typename = '_'.join(parts)
  54. if hasattr(self, 'repr_' + typename):
  55. return getattr(self, 'repr_' + typename)(x, level)
  56. else:
  57. return self.repr_instance(x, level)
  58. def _join(self, pieces, level):
  59. if self.indent is None:
  60. return ', '.join(pieces)
  61. if not pieces:
  62. return ''
  63. indent = self.indent
  64. if isinstance(indent, int):
  65. if indent < 0:
  66. raise ValueError(
  67. f'Repr.indent cannot be negative int (was {indent!r})'
  68. )
  69. indent *= ' '
  70. try:
  71. sep = ',\n' + (self.maxlevel - level + 1) * indent
  72. except TypeError as error:
  73. raise TypeError(
  74. f'Repr.indent must be a str, int or None, not {type(indent)}'
  75. ) from error
  76. return sep.join(('', *pieces, ''))[1:-len(indent) or None]
  77. def _repr_iterable(self, x, level, left, right, maxiter, trail=''):
  78. n = len(x)
  79. if level <= 0 and n:
  80. s = self.fillvalue
  81. else:
  82. newlevel = level - 1
  83. repr1 = self.repr1
  84. pieces = [repr1(elem, newlevel) for elem in islice(x, maxiter)]
  85. if n > maxiter:
  86. pieces.append(self.fillvalue)
  87. s = self._join(pieces, level)
  88. if n == 1 and trail and self.indent is None:
  89. right = trail + right
  90. return '%s%s%s' % (left, s, right)
  91. def repr_tuple(self, x, level):
  92. return self._repr_iterable(x, level, '(', ')', self.maxtuple, ',')
  93. def repr_list(self, x, level):
  94. return self._repr_iterable(x, level, '[', ']', self.maxlist)
  95. def repr_array(self, x, level):
  96. if not x:
  97. return "array('%s')" % x.typecode
  98. header = "array('%s', [" % x.typecode
  99. return self._repr_iterable(x, level, header, '])', self.maxarray)
  100. def repr_set(self, x, level):
  101. if not x:
  102. return 'set()'
  103. x = _possibly_sorted(x)
  104. return self._repr_iterable(x, level, '{', '}', self.maxset)
  105. def repr_frozenset(self, x, level):
  106. if not x:
  107. return 'frozenset()'
  108. x = _possibly_sorted(x)
  109. return self._repr_iterable(x, level, 'frozenset({', '})',
  110. self.maxfrozenset)
  111. def repr_deque(self, x, level):
  112. return self._repr_iterable(x, level, 'deque([', '])', self.maxdeque)
  113. def repr_dict(self, x, level):
  114. n = len(x)
  115. if n == 0:
  116. return '{}'
  117. if level <= 0:
  118. return '{' + self.fillvalue + '}'
  119. newlevel = level - 1
  120. repr1 = self.repr1
  121. pieces = []
  122. for key in islice(_possibly_sorted(x), self.maxdict):
  123. keyrepr = repr1(key, newlevel)
  124. valrepr = repr1(x[key], newlevel)
  125. pieces.append('%s: %s' % (keyrepr, valrepr))
  126. if n > self.maxdict:
  127. pieces.append(self.fillvalue)
  128. s = self._join(pieces, level)
  129. return '{%s}' % (s,)
  130. def repr_str(self, x, level):
  131. s = builtins.repr(x[:self.maxstring])
  132. if len(s) > self.maxstring:
  133. i = max(0, (self.maxstring-3)//2)
  134. j = max(0, self.maxstring-3-i)
  135. s = builtins.repr(x[:i] + x[len(x)-j:])
  136. s = s[:i] + self.fillvalue + s[len(s)-j:]
  137. return s
  138. def repr_int(self, x, level):
  139. s = builtins.repr(x) # XXX Hope this isn't too slow...
  140. if len(s) > self.maxlong:
  141. i = max(0, (self.maxlong-3)//2)
  142. j = max(0, self.maxlong-3-i)
  143. s = s[:i] + self.fillvalue + s[len(s)-j:]
  144. return s
  145. def repr_instance(self, x, level):
  146. try:
  147. s = builtins.repr(x)
  148. # Bugs in x.__repr__() can cause arbitrary
  149. # exceptions -- then make up something
  150. except Exception:
  151. return '<%s instance at %#x>' % (x.__class__.__name__, id(x))
  152. if len(s) > self.maxother:
  153. i = max(0, (self.maxother-3)//2)
  154. j = max(0, self.maxother-3-i)
  155. s = s[:i] + self.fillvalue + s[len(s)-j:]
  156. return s
  157. def _possibly_sorted(x):
  158. # Since not all sequences of items can be sorted and comparison
  159. # functions may raise arbitrary exceptions, return an unsorted
  160. # sequence in that case.
  161. try:
  162. return sorted(x)
  163. except Exception:
  164. return list(x)
  165. aRepr = Repr()
  166. repr = aRepr.repr