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:

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.

_format_repr_exception(exc: BaseException, obj: object) -> str

Formats a string indicating that an exception occurred while calling `repr()` on an object.

_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).


Class: SafeRepr

A subclass of `reprlib.Repr` that produces safe and optionally size-limited `repr` strings.

Description

Constructor

SafeRepr(maxsize: int | None, use_ascii: bool = False) -> None

Methods


Functions

safeformat(obj: object) -> str

Returns a pretty-printed string representation of `obj` using `pprint.pformat`.

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`.

saferepr_unlimited(obj: object, use_ascii: bool = True) -> str

Returns a safe `repr` string for `obj` without size limitation.


Important Implementation Details


Interaction with Other Components


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.