blob: 40d991fa3648eaf9ba2614eb03b5bfadb4446956 [file] [log] [blame]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001"""Redo the builtin repr() (representation) but with limits on most sizes."""
Guido van Rossumbabe2bf1992-01-22 22:21:31 +00002
Raymond Hettinger98a5f3f2010-09-13 21:36:00 +00003__all__ = ["Repr", "repr", "recursive_repr"]
Skip Montanaro0de65802001-02-15 22:15:14 +00004
Georg Brandl1a3284e2007-12-02 09:40:06 +00005import builtins
Raymond Hettingerba6cd362004-05-21 10:00:15 +00006from itertools import islice
Raymond Hettinger98a5f3f2010-09-13 21:36:00 +00007try:
Antoine Pitroubb0ad4c2011-10-11 18:51:53 +02008 from _thread import get_ident
Brett Cannoncd171c82013-07-04 17:43:24 -04009except ImportError:
Raymond Hettinger98a5f3f2010-09-13 21:36:00 +000010 from _dummy_thread import get_ident
11
12def recursive_repr(fillvalue='...'):
13 'Decorator to make a repr function return fillvalue for a recursive call'
14
15 def decorating_function(user_function):
16 repr_running = set()
17
18 def wrapper(self):
19 key = id(self), get_ident()
20 if key in repr_running:
21 return fillvalue
22 repr_running.add(key)
23 try:
24 result = user_function(self)
25 finally:
26 repr_running.discard(key)
27 return result
28
29 # Can't use functools.wraps() here because of bootstrap issues
30 wrapper.__module__ = getattr(user_function, '__module__')
31 wrapper.__doc__ = getattr(user_function, '__doc__')
32 wrapper.__name__ = getattr(user_function, '__name__')
Serhiy Storchakab3b366d2016-04-26 09:30:44 +030033 wrapper.__qualname__ = getattr(user_function, '__qualname__')
Raymond Hettinger6ef18f42011-01-23 21:33:36 +000034 wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
Raymond Hettinger98a5f3f2010-09-13 21:36:00 +000035 return wrapper
36
37 return decorating_function
Walter Dörwald70a6b492004-02-12 17:35:32 +000038
Guido van Rossumbabe2bf1992-01-22 22:21:31 +000039class Repr:
Raymond Hettingerba6cd362004-05-21 10:00:15 +000040
Tim Peters0c9886d2001-01-15 01:18:21 +000041 def __init__(self):
42 self.maxlevel = 6
43 self.maxtuple = 6
44 self.maxlist = 6
Tim Peters6ee04802003-02-05 18:29:34 +000045 self.maxarray = 5
Tim Peters0c9886d2001-01-15 01:18:21 +000046 self.maxdict = 4
Raymond Hettingerba6cd362004-05-21 10:00:15 +000047 self.maxset = 6
48 self.maxfrozenset = 6
Raymond Hettinger1453e4a2004-05-21 23:01:18 +000049 self.maxdeque = 6
Tim Peters0c9886d2001-01-15 01:18:21 +000050 self.maxstring = 30
51 self.maxlong = 40
Guido van Rossuma48a3b42006-04-20 16:07:39 +000052 self.maxother = 30
Raymond Hettingerba6cd362004-05-21 10:00:15 +000053
Tim Peters0c9886d2001-01-15 01:18:21 +000054 def repr(self, x):
55 return self.repr1(x, self.maxlevel)
Raymond Hettingerba6cd362004-05-21 10:00:15 +000056
Tim Peters0c9886d2001-01-15 01:18:21 +000057 def repr1(self, x, level):
Guido van Rossuma995c912001-08-09 18:56:27 +000058 typename = type(x).__name__
Tim Peters0c9886d2001-01-15 01:18:21 +000059 if ' ' in typename:
Eric S. Raymond6b71e742001-02-09 08:56:30 +000060 parts = typename.split()
61 typename = '_'.join(parts)
Tim Peters0c9886d2001-01-15 01:18:21 +000062 if hasattr(self, 'repr_' + typename):
63 return getattr(self, 'repr_' + typename)(x, level)
64 else:
Guido van Rossuma48a3b42006-04-20 16:07:39 +000065 return self.repr_instance(x, level)
Raymond Hettingerba6cd362004-05-21 10:00:15 +000066
Raymond Hettinger1453e4a2004-05-21 23:01:18 +000067 def _repr_iterable(self, x, level, left, right, maxiter, trail=''):
Raymond Hettingerba6cd362004-05-21 10:00:15 +000068 n = len(x)
69 if level <= 0 and n:
70 s = '...'
71 else:
72 newlevel = level - 1
73 repr1 = self.repr1
74 pieces = [repr1(elem, newlevel) for elem in islice(x, maxiter)]
75 if n > maxiter: pieces.append('...')
76 s = ', '.join(pieces)
Raymond Hettinger1453e4a2004-05-21 23:01:18 +000077 if n == 1 and trail: right = trail + right
Raymond Hettingerba6cd362004-05-21 10:00:15 +000078 return '%s%s%s' % (left, s, right)
79
Tim Peters0c9886d2001-01-15 01:18:21 +000080 def repr_tuple(self, x, level):
Guido van Rossumcd16bf62007-06-13 18:07:49 +000081 return self._repr_iterable(x, level, '(', ')', self.maxtuple, ',')
Raymond Hettingerba6cd362004-05-21 10:00:15 +000082
Tim Peters0c9886d2001-01-15 01:18:21 +000083 def repr_list(self, x, level):
Raymond Hettingerba6cd362004-05-21 10:00:15 +000084 return self._repr_iterable(x, level, '[', ']', self.maxlist)
Tim Peters6ee04802003-02-05 18:29:34 +000085
86 def repr_array(self, x, level):
Raymond Hettingera34cd0c2014-11-15 10:58:58 -080087 if not x:
88 return "array('%s')" % x.typecode
Tim Peters6ee04802003-02-05 18:29:34 +000089 header = "array('%s', [" % x.typecode
Raymond Hettingerba6cd362004-05-21 10:00:15 +000090 return self._repr_iterable(x, level, header, '])', self.maxarray)
91
92 def repr_set(self, x, level):
Raymond Hettingerffd842e2014-11-09 22:30:36 -080093 if not x:
94 return 'set()'
Thomas Wouters1b7f8912007-09-19 03:06:30 +000095 x = _possibly_sorted(x)
Raymond Hettingerffd842e2014-11-09 22:30:36 -080096 return self._repr_iterable(x, level, '{', '}', self.maxset)
Raymond Hettingerba6cd362004-05-21 10:00:15 +000097
98 def repr_frozenset(self, x, level):
Raymond Hettingerffd842e2014-11-09 22:30:36 -080099 if not x:
100 return 'frozenset()'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000101 x = _possibly_sorted(x)
Raymond Hettingerffd842e2014-11-09 22:30:36 -0800102 return self._repr_iterable(x, level, 'frozenset({', '})',
Raymond Hettingerba6cd362004-05-21 10:00:15 +0000103 self.maxfrozenset)
Tim Peters6ee04802003-02-05 18:29:34 +0000104
Raymond Hettinger1453e4a2004-05-21 23:01:18 +0000105 def repr_deque(self, x, level):
106 return self._repr_iterable(x, level, 'deque([', '])', self.maxdeque)
107
Tim Petersa427a2b2001-10-29 22:25:45 +0000108 def repr_dict(self, x, level):
Tim Peters0c9886d2001-01-15 01:18:21 +0000109 n = len(x)
110 if n == 0: return '{}'
111 if level <= 0: return '{...}'
Raymond Hettingerba6cd362004-05-21 10:00:15 +0000112 newlevel = level - 1
113 repr1 = self.repr1
114 pieces = []
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000115 for key in islice(_possibly_sorted(x), self.maxdict):
Raymond Hettingerba6cd362004-05-21 10:00:15 +0000116 keyrepr = repr1(key, newlevel)
117 valrepr = repr1(x[key], newlevel)
118 pieces.append('%s: %s' % (keyrepr, valrepr))
119 if n > self.maxdict: pieces.append('...')
120 s = ', '.join(pieces)
121 return '{%s}' % (s,)
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123 def repr_str(self, x, level):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000124 s = builtins.repr(x[:self.maxstring])
Tim Peters0c9886d2001-01-15 01:18:21 +0000125 if len(s) > self.maxstring:
Guido van Rossum54e54c62001-09-04 19:14:14 +0000126 i = max(0, (self.maxstring-3)//2)
Tim Peters0c9886d2001-01-15 01:18:21 +0000127 j = max(0, self.maxstring-3-i)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000128 s = builtins.repr(x[:i] + x[len(x)-j:])
Tim Peters0c9886d2001-01-15 01:18:21 +0000129 s = s[:i] + '...' + s[len(s)-j:]
130 return s
Raymond Hettingerba6cd362004-05-21 10:00:15 +0000131
Guido van Rossum4c9695a2007-01-15 00:14:39 +0000132 def repr_int(self, x, level):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000133 s = builtins.repr(x) # XXX Hope this isn't too slow...
Tim Peters0c9886d2001-01-15 01:18:21 +0000134 if len(s) > self.maxlong:
Guido van Rossum54e54c62001-09-04 19:14:14 +0000135 i = max(0, (self.maxlong-3)//2)
Tim Peters0c9886d2001-01-15 01:18:21 +0000136 j = max(0, self.maxlong-3-i)
137 s = s[:i] + '...' + s[len(s)-j:]
138 return s
Raymond Hettingerba6cd362004-05-21 10:00:15 +0000139
Tim Peters0c9886d2001-01-15 01:18:21 +0000140 def repr_instance(self, x, level):
141 try:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000142 s = builtins.repr(x)
Tim Peters0c9886d2001-01-15 01:18:21 +0000143 # Bugs in x.__repr__() can cause arbitrary
144 # exceptions -- then make up something
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000145 except Exception:
Serhiy Storchaka0c937b32014-07-22 12:14:52 +0300146 return '<%s instance at %#x>' % (x.__class__.__name__, id(x))
Guido van Rossuma48a3b42006-04-20 16:07:39 +0000147 if len(s) > self.maxother:
148 i = max(0, (self.maxother-3)//2)
149 j = max(0, self.maxother-3-i)
Tim Peters0c9886d2001-01-15 01:18:21 +0000150 s = s[:i] + '...' + s[len(s)-j:]
151 return s
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000152
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000153
154def _possibly_sorted(x):
155 # Since not all sequences of items can be sorted and comparison
156 # functions may raise arbitrary exceptions, return an unsorted
157 # sequence in that case.
158 try:
159 return sorted(x)
160 except Exception:
161 return list(x)
162
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000163aRepr = Repr()
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000164repr = aRepr.repr