| 1 |
import py |
| 2 |
import sys |
| 3 |
|
| 4 |
builtin_repr = repr |
| 5 |
|
| 6 |
reprlib = py.builtin._tryimport('repr', 'reprlib') |
| 7 |
|
| 8 |
class SafeRepr(reprlib.Repr): |
| 9 |
""" subclass of repr.Repr that limits the resulting size of repr() |
| 10 |
and includes information on exceptions raised during the call. |
| 11 |
""" |
| 12 |
def repr(self, x): |
| 13 |
return self._callhelper(reprlib.Repr.repr, self, x) |
| 14 |
|
| 15 |
def repr_unicode(self, x, level): |
| 16 |
|
| 17 |
def repr(u): |
| 18 |
if "'" not in u: |
| 19 |
return py.builtin._totext("'%s'") % u |
| 20 |
elif '"' not in u: |
| 21 |
return py.builtin._totext('"%s"') % u |
| 22 |
else: |
| 23 |
return py.builtin._totext("'%s'") % u.replace("'", r"\'") |
| 24 |
|
| 25 |
repr = builtin_repr |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
s = repr(x[:self.maxstring]) |
| 30 |
if len(s) > self.maxstring: |
| 31 |
i = max(0, (self.maxstring-3)//2) |
| 32 |
j = max(0, self.maxstring-3-i) |
| 33 |
s = repr(x[:i] + x[len(x)-j:]) |
| 34 |
s = s[:i] + '...' + s[len(s)-j:] |
| 35 |
return s |
| 36 |
|
| 37 |
def repr_instance(self, x, level): |
| 38 |
return self._callhelper(builtin_repr, x) |
| 39 |
|
| 40 |
def _callhelper(self, call, x, *args): |
| 41 |
try: |
| 42 |
|
| 43 |
s = call(x, *args) |
| 44 |
except py.builtin._sysex: |
| 45 |
raise |
| 46 |
except: |
| 47 |
cls, e, tb = sys.exc_info() |
| 48 |
exc_name = getattr(cls, '__name__', 'unknown') |
| 49 |
try: |
| 50 |
exc_info = str(e) |
| 51 |
except py.builtin._sysex: |
| 52 |
raise |
| 53 |
except: |
| 54 |
exc_info = 'unknown' |
| 55 |
return '<[%s("%s") raised in repr()] %s object at 0x%x>' % ( |
| 56 |
exc_name, exc_info, x.__class__.__name__, id(x)) |
| 57 |
else: |
| 58 |
if len(s) > self.maxsize: |
| 59 |
i = max(0, (self.maxsize-3)//2) |
| 60 |
j = max(0, self.maxsize-3-i) |
| 61 |
s = s[:i] + '...' + s[len(s)-j:] |
| 62 |
return s |
| 63 |
|
| 64 |
def saferepr(obj, maxsize=240): |
| 65 |
""" return a size-limited safe repr-string for the given object. |
| 66 |
Failing __repr__ functions of user instances will be represented |
| 67 |
with a short exception info and 'saferepr' generally takes |
| 68 |
care to never raise exceptions itself. This function is a wrapper |
| 69 |
around the Repr/reprlib functionality of the standard 2.6 lib. |
| 70 |
""" |
| 71 |
|
| 72 |
srepr = SafeRepr() |
| 73 |
srepr.maxstring = maxsize |
| 74 |
srepr.maxsize = maxsize |
| 75 |
srepr.maxother = 160 |
| 76 |
return srepr.repr(obj) |