Cheap Repr

0.5.2 · active · verified Thu Apr 16

cheap-repr is a Python library that provides a more efficient, configurable, and short string representation of objects, improving upon the standard library's `reprlib`. It offers an easy API to register custom representation functions for various classes. The current version is 0.5.2, released on August 10, 2024, and the project appears to be actively maintained.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `cheap_repr` to get a condensed string representation of an object, including registering a custom repr function for your own classes using `@register_repr`. It also shows how `suppression_threshold` can be adjusted on the `cheap_repr` function itself.

from cheap_repr import cheap_repr, register_repr

class MyClass:
    def __init__(self, items):
        self.items = items

@register_repr(MyClass)
def repr_my_class(x, helper):
    return helper.repr_iterable(x.items, 'MyClass([', '])')


# Example usage with cheap_repr
obj1 = MyClass(list(range(1000)))
print(f"Custom repr: {cheap_repr(obj1)}")

# Example with default cheap_repr behavior for a built-in list
long_list = list(range(100))
print(f"List repr: {cheap_repr(long_list)}")

# Adjusting suppression threshold on the function itself
cheap_repr.suppression_threshold = 50 # Temporarily reduce threshold
print(f"List repr (short threshold): {cheap_repr(long_list)}")
cheap_repr.suppression_threshold = 300 # Reset to default

# Using basic_repr for a class
class AnotherClass:
    def __init__(self, value):
        self.value = value

# Register basic_repr for AnotherClass
register_repr(AnotherClass)(basic_repr)
obj2 = AnotherClass(123)
print(f"Basic repr: {cheap_repr(obj2)}")

view raw JSON →