Better version of repr/reprlib for short, cheap string representations.
Slowing down. Last release over 2 years ago, little activity since. Fine for existing code; think twice for a new project.
pip install cheap-reprcheap_repr
This library provides short, fast, configurable string representations, and an easy API for registering your own. It's an improvement of the standard library module reprlib (repr in Python 2).
Just use the cheap_repr function instead of repr:
>>> from cheap_repr import cheap_repr
>>> cheap_repr(list(range(100)))
'[0, 1, 2, ..., 97, 98, 99]'
cheap_repr knows how to handle many different types out of the box. You can register a function for any type, and pull requests to make these part of the library are welcome. If it doesn't know how to handle a particular type, the default repr() is used, possibly truncated:
>>> class MyClass(object):
... def __init__(self, items):
... self.items = items
...
... def __repr__(self):
... return 'MyClass(%r)' % self.items
...
>>> c = MyClass(list(range(20)))
>>> c
MyClass([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> cheap_repr(c)
'MyClass([0, 1, 2, 3, 4, 5, 6... 13, 14, 15, 16, 17, 18, 19])'
Suppression of long reprs
cheap_repr is meant to prevent slow, expensive computations of string representations. So if it finds that a particular class can potentially produce very long representations, the class will be suppressed, meaning that in future the __repr__ won't be calculated at all:
>>> cheap_repr(MyClass(list(range(1000))))
'MyClass([0, 1, 2, 3, 4, 5, 6...94, 995, 996, 997, 998, 999])'
.../cheap_repr/__init__.py:80: ReprSuppressedWarning: MyClass.__repr__ is too long and has been suppressed. Register a repr for the class to avoid this warning and see an informative repr again, or increase cheap_repr.suppression_threshold
>>> cheap_repr(MyClass(list(range(1000))))
'<MyClass instance at 0x1034de7f0 (repr suppressed)>'
cheap_repr.suppression_threshold refers to the attribute on the function itself, not the module. By default it's 300, meaning that a longer than 300 characters will trigger the suppression.