saferepr.py
Overview
The [saferepr.py](/projects/286/67487) module provides utility functionality to generate safe and size-limited string representations (`repr`) of Python objects. It enhances the standard `repr()` by addressing two main issues:
Handling exceptions raised during
repr()calls: If an object's__repr__method raises an exception,safereprreturns a descriptive placeholder string instead of propagating the exception.Limiting the size of the representation: Large or deeply nested objects can produce excessively long
reprstrings. The module truncates these strings intelligently with ellipses to keep outputs concise and readable.
This makes [saferepr.py](/projects/286/67487) particularly useful in contexts such as debugging, logging, and assertion error reporting, where robustness and readability of object representations are critical.
Module Contents
Helper Functions
_try_repr_or_str(obj: object) -> str
Attempts to return `repr(obj)`. If any exception (other than [KeyboardInterrupt](/projects/286/67223) or `SystemExit`) is raised during `repr`, it falls back to returning a string showing the object's type and its string representation.
Parameters:
obj: The object to represent.
Returns: A string representation of the object or a fallback string if
reprfails.Usage: Internal helper for safe attempts at object representation.
_format_repr_exception(exc: BaseException, obj: object) -> str
Formats a string indicating that an exception occurred while calling `repr()` on an object.
Parameters:
exc: The exception instance raised duringrepr.obj: The object whosereprfailed.
Returns: A formatted string such as
<[ValueError('bad repr') raised in repr()] ClassName object at 0x...>.Usage: Used internally to produce informative placeholders when
reprfails.
_ellipsize(s: str, maxsize: int) -> str
Truncates a string `s` to a maximum length `maxsize` by removing characters from the middle and replacing them with `...` (ellipsis).
Parameters:
s: The original string.maxsize: Maximum allowed length.
Returns: The truncated string with ellipsis if
sexceedsmaxsize; otherwise returnssunchanged.Example:
_ellipsize('abcdefghijklmnop', 10) # returns 'abc...nop'Usage: Used internally to enforce size limits on repr strings.
Class: SafeRepr
A subclass of `reprlib.Repr` that produces safe and optionally size-limited `repr` strings.
Description
Extends the standard library's
reprlib.Reprto:Limit output size via truncation and ellipses.
Include information about exceptions raised during
reprcalls.Optionally use
ascii()instead ofrepr()to force ASCII-only output.
Constructor
SafeRepr(maxsize: int | None, use_ascii: bool = False) -> None
Parameters:
maxsize: If set, truncates resulting repr strings to this length; ifNone, no truncation is applied.use_ascii: IfTrue, usesascii()instead ofrepr()for string conversion.
Behavior: Sets internal limits accordingly and initializes the superclass.
Methods
repr(self, x: object) -> strReturns a safe
reprstring of the objectx.Attempts to use
ascii(x)or superclassreprbased onuse_ascii.Catches exceptions from
reprand returns a formatted placeholder.Truncates the result to
maxsizeif applicable.
repr_instance(self, x: object, level: int) -> strProvides a safe representation for general instances.
Attempts standard
repr(x).Handles exceptions similarly.
Applies size truncation if necessary.
Functions
safeformat(obj: object) -> str
Returns a pretty-printed string representation of `obj` using `pprint.pformat`.
If
pprint.pformatfails (due toreprexceptions inside), falls back to the exception-aware placeholder string.Usage: Useful for readable multi-line representations with safety against failing
__repr__.
saferepr(obj: object, maxsize: int | None = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False) -> str
Returns a safe and size-limited `repr` string for `obj`.
Wraps the
SafeReprclass with default max size of 240 characters.Handles exceptions in
repr.By default, returns a truncated representation with ellipses if too long.
Parameters:
obj: Object to represent.maxsize: Maximum length of the resulting string (default 240).use_ascii: Whether to use ASCII-only representation.
Returns: Safe string representation.
saferepr_unlimited(obj: object, use_ascii: bool = True) -> str
Returns a safe `repr` string for `obj` without size limitation.
Uses
ascii()orrepr()directly.Catches exceptions and returns a placeholder if
reprfails.Parameters:
obj: Object to represent.use_ascii: Whether to use ASCII-only representation (defaultTrue).
Returns: Full (unlimited size) safe
reprstring.
Important Implementation Details
The module gracefully handles exceptions in
reprcalls, which is a common source of errors when debugging complex objects.Size truncation is done by replacing the middle part of the string with an ellipsis (
...), preserving both the start and end of the string for better context.The class
SafeReprleverages Python's built-inreprlib.Reprfor recursive and size-limited representations, extending it to add exception safety and ASCII options.The use of
ascii()enforces escaping of non-ASCII characters, helpful in environments that require ASCII-only output.
Interaction with Other Components
This module is a utility that can be imported anywhere in the system where robust object string representations are needed.
It is especially useful in:
Assertion error messages (e.g., testing frameworks).
Logging or debugging output where an object's
reprmay fail or produce large output.Any diagnostic tools that introspect objects.
Can be seamlessly integrated with other modules that require pretty-printing or safe display of arbitrary Python objects.
Usage Examples
import saferepr
class BadRepr:
def __repr__(self):
raise ValueError("Cannot represent this object")
obj = BadRepr()
print(saferepr.saferepr(obj))
# Output: something like
# <[ValueError('Cannot represent this object') raised in repr()] BadRepr object at 0x...>
large_list = list(range(1000))
print(saferepr.saferepr(large_list, maxsize=50))
# Output: '[0, 1, 2, 3, ... 997, 998, 999]'
print(saferepr.safeformat({'key': large_list}))
# Pretty-printed dict with safe repr of large_list
Visual Diagram
classDiagram
class SafeRepr {
-maxstring: int
-maxsize: int | None
-use_ascii: bool
+__init__(maxsize: int | None, use_ascii: bool = False)
+repr(x: object) str
+repr_instance(x: object, level: int) str
}
classFunctions <|-- SafeRepr
classFunctions : +_try_repr_or_str(obj: object) str
classFunctions : +_format_repr_exception(exc: BaseException, obj: object) str
classFunctions : +_ellipsize(s: str, maxsize: int) str
classFunctions : +safeformat(obj: object) str
classFunctions : +saferepr(obj: object, maxsize: int | None, use_ascii: bool) str
classFunctions : +saferepr_unlimited(obj: object, use_ascii: bool) str
Summary
The [saferepr.py](/projects/286/67487) module provides robust, safe, and configurable `repr`-style string generation. It protects against exceptions from faulty `__repr__` implementations and prevents overly verbose outputs through truncation. This makes it ideal for diagnostic and debugging output in complex Python applications.