Skip to content
Python Basics: Bound Diagnostic Representations with reprlib

Python Basics: Bound Diagnostic Representations with reprlib

October 28, 2026

A diagnostic line should not dump an entire large collection. Configure representation limits, then protect a custom representation against a self-reference.

Prepare a scratch directory

Tested on Linux with CPython 3.12.14. You need Bash, a text editor, the named runtime, and standard mktemp, rm, and rmdir utilities. Run Python without -O so assertions remain enabled. The examples use only controlled local data; generated fixture directories are cleaned automatically.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save this as demonstrate-reprlib.py:

import reprlib

formatter = reprlib.Repr()
formatter.maxlist = 3
formatter.maxstring = 16
print("List:", formatter.repr(list(range(8))))
print("Text:", formatter.repr("abcdefghijklmnopqrstuvwxyz"))
assert formatter.repr(list(range(8))) == "[0, 1, 2, ...]"

class Link:
    def __init__(self):
        self.next = self

    @reprlib.recursive_repr(fillvalue="<cycle>")
    def __repr__(self):
        return f"Link(next={self.next!r})"

link = Link()
assert repr(link) == "Link(next=<cycle>)"
print("Recursive object:", link)

Run it:

python3 -B demonstrate-reprlib.py

Observed output:

List: [0, 1, 2, ...]
Text: 'abcde...uvwxyz'
Recursive object: Link(next=<cycle>)

Read the result

The list limit controls the number of displayed elements. The string representation keeps a shortened preview. recursive_repr detects reentry for the same object and thread, replacing the cycle instead of recursing indefinitely.

Apply it carefully

Truncation is not redaction: secrets may remain in the visible prefix or suffix. Custom repr methods can still execute arbitrary application code. These limits make diagnostics smaller, but they do not provide a universal CPU or memory budget for untrusted objects.

The official reference describes the behavior and options. These checks cover the fixture above rather than every input or platform.

Clean up

Remove the saved source, return to the starting directory, then remove the empty practice directory:

rm -- demonstrate-reprlib.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect its remaining contents rather than deleting unknown files.

Acknowledgements

This post was created with assistance from AI.

Last updated on