From 0482853d968637db73a19aeb8ca06934156d748e Mon Sep 17 00:00:00 2001 From: Ram Rachum Date: Thu, 9 May 2019 09:15:59 +0300 Subject: [PATCH] Remove `reprlib` because it's not reliable for simple cases --- pysnooper/utils.py | 49 ++++++++++++++--------------------------- tests/test_pysnooper.py | 6 ++--- 2 files changed, 20 insertions(+), 35 deletions(-) diff --git a/pysnooper/utils.py b/pysnooper/utils.py index 91e855f..37ff848 100644 --- a/pysnooper/utils.py +++ b/pysnooper/utils.py @@ -6,13 +6,7 @@ import abc from .pycompat import ABC from .third_party import six -try: - import reprlib - import builtins -except ImportError: - import repr as reprlib - import __builtin__ as builtins - +MAX_VARIABLE_LENGTH = 100 def _check_methods(C, *methods): mro = C.__mro__ @@ -54,36 +48,27 @@ def shitcode(s): ) -class Repr(reprlib.Repr, object): # reprlib.Repr is old-style in Python 2 - def __init__(self): - super(Repr, self).__init__() - self.maxother = 100 - - def repr(self, x): - try: - return super(Repr, self).repr(x) - except Exception as e: - return '<{} instance at {:#x} (__repr__ raised {})>'.format( - x.__class__.__name__, id(x), e.__class__.__name__) - - def repr_instance(self, x, level): - s = builtins.repr(x) - if len(s) > self.maxother: - i = max(0, (self.maxother - 3) // 2) - j = max(0, self.maxother - 3 - i) - s = s[:i] + '...' + s[len(s) - j:] - return s - - -repr_instance = Repr() - - def get_shortish_repr(item): - r = repr_instance.repr(item) + try: + r = repr(item) + except Exception: + r = 'REPR FAILED' r = r.replace('\r', '').replace('\n', '') + if len(r) > MAX_VARIABLE_LENGTH: + r = '{truncated_r}...'.format(truncated_r=r[:MAX_VARIABLE_LENGTH]) return r + + + + + + + + + + def ensure_tuple(x): if isinstance(x, six.string_types): x = (x,) diff --git a/tests/test_pysnooper.py b/tests/test_pysnooper.py index 951131b..2cbc477 100644 --- a/tests/test_pysnooper.py +++ b/tests/test_pysnooper.py @@ -280,10 +280,10 @@ def test_long_variable(): ( CallEntry('def my_function():'), LineEntry('foo = list(range(1000))'), - VariableEntry('foo', '[0, 1, 2, 3, 4, 5, ...]'), + VariableEntry('foo', value_regex=r'''^\[0, 1, 2, .*\.\.\.$'''), LineEntry(), ReturnEntry(), - ReturnValueEntry('[0, 1, 2, 3, 4, 5, ...]') + ReturnValueEntry(value_regex=r'''^\[0, 1, 2, .*\.\.\.$''') ) ) @@ -308,7 +308,7 @@ def test_repr_exception(): VariableEntry('Bad'), CallEntry('def my_function():'), LineEntry('bad = Bad()'), - VariableEntry('bad', value_regex=r''), + VariableEntry('bad', value='REPR FAILED'), ReturnEntry(), ReturnValueEntry('None') )