reprlib.py 6.4 KB

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