From 5f666c99b71694d3afcb595ebc57ac66301d2e53 Mon Sep 17 00:00:00 2001 From: hpk Date: Thu, 21 Aug 2008 11:48:46 +0200 Subject: [PATCH] [svn r57535] extending hacks for a safe representation of objects to also work for broken __repr__s on newstyle classes. --HG-- branch : trunk --- py/code/excinfo.py | 2 +- py/code/safe_repr.py | 10 +++++++++- py/code/testing/test_safe_repr.py | 9 +++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/py/code/excinfo.py b/py/code/excinfo.py index ce3c712ef..06a47bbc7 100644 --- a/py/code/excinfo.py +++ b/py/code/excinfo.py @@ -153,7 +153,7 @@ class FormattedExcinfo(object): else: # This formatting could all be handled by the _repr() function, which is # only repr.Repr in disguise, so is very configurable. - str_repr = safe_repr._repr(value) + str_repr = self._saferepr(value) #if len(str_repr) < 70 or not isinstance(value, # (list, tuple, dict)): lines.append("%-10s = %s" %(name, str_repr)) diff --git a/py/code/safe_repr.py b/py/code/safe_repr.py index 86a03caa2..cf5e3098b 100644 --- a/py/code/safe_repr.py +++ b/py/code/safe_repr.py @@ -30,10 +30,17 @@ class SafeRepr(repr.Repr): # Do we need a commandline switch for this? self.maxstring = 240 # 3 * 80 chars self.maxother = 160 # 2 * 80 chars + + def repr(self, x): + return self._callhelper(repr.Repr.repr, self, x) + def repr_instance(self, x, level): + return self._callhelper(__builtin__.repr, x) + + def _callhelper(self, call, x, *args): try: # Try the vanilla repr and make sure that the result is a string - s = str(__builtin__.repr(x)) + s = call(x, *args) except (KeyboardInterrupt, MemoryError, SystemExit): raise except Exception ,e: @@ -60,4 +67,5 @@ class SafeRepr(repr.Repr): s = s[:i] + '...' + s[len(s)-j:] return s + _repr = SafeRepr().repr diff --git a/py/code/testing/test_safe_repr.py b/py/code/testing/test_safe_repr.py index 4d67ed14b..955184601 100644 --- a/py/code/testing/test_safe_repr.py +++ b/py/code/testing/test_safe_repr.py @@ -35,5 +35,14 @@ def test_big_repr(): assert len(safe_repr._repr(range(1000))) <= \ len('[' + safe_repr.SafeRepr().maxlist * "1000" + ']') +def test_repr_on_newstyle(): + class Function(object): + def __repr__(self): + return "<%s>" %(self.name) + try: + s = safe_repr._repr(Function()) + except Exception, e: + py.test.fail("saferepr failed for newstyle class") +