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.
pip install cheap-reprVerified import paths — ran on the pinned version, not inferred.
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.
Access and modify `cheap_repr.suppression_threshold` or `cheap_repr.max_level` directly on the imported function object (e.g., `cheap_repr.suppression_threshold = 50`). Be aware that the `level` argument in a `cheap_repr()` call will override `max_level`.
If you want `cheap_repr` to respect a class's `__repr__` method, you need to explicitly register `normal_repr` for that class using `@register_repr(MyClass)(normal_repr)`. For custom formatting that integrates `cheap_repr`'s features (like level handling), define and register a custom `repr` function that utilizes the `helper` object.
Add `from cheap_repr import cheap_repr` at the beginning of your Python file.
To make `cheap_repr` use your class's `__repr__` for specific types, register `normal_repr` for that class: `from cheap_repr import register_repr, normal_repr; @register_repr(MyClass)(normal_repr)`. For custom, length-aware representations, write and register a dedicated function: `from cheap_repr import register_repr; @register_repr(MyClass) def my_custom_repr(obj, helper): return helper.repr_iterable(obj.items, 'MyClass(', ')')`.Ensure you are modifying the attributes on the *imported* `cheap_repr` function directly (e.g., `from cheap_repr import cheap_repr; cheap_repr.max_level = 5`). Remember that an explicit `level` argument in `cheap_repr(obj, level=...)` will always take precedence over `cheap_repr.max_level`.