On this page
  1. reprlib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Customizing Limits with a Repr Instance
  7. 2. Guarding Custom Containers Against Circular __repr__
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

reprlib

Prev: readline | Up: stdlib_module | Next: resource
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org — reprlib
Tags: #public #python3 #stdlib


Import

import reprlib

Overview

Size-bounded repr() generator (Repr, reprlib.repr(), @recursive_repr) that truncates long strings, deep nested containers, and circular references into compact summaries. Use reprlib in logging, debuggers, and custom __repr__ methods so massive data structures don't flood logs or trigger RecursionError.

Quick Start

import reprlib

big = list(range(1000))
assert reprlib.repr(big) == "[0, 1, 2, 3, 4, 5, ...]"

Implementation Walkthrough

1. Customizing Limits with a Repr Instance

Instantiate reprlib.Repr to tune maxlevel, maxlist, maxdict, maxstring, or enable pretty indentation (indent=2):

import reprlib

short = reprlib.Repr(maxlist=3, maxstring=12)
assert short.repr([1, 2, 3, 4, 5]) == "[1, 2, 3, ...]"
assert short.repr("abcdefghijklmnopqrstuvwxyz") == "'abc...xyz'"

2. Guarding Custom Containers Against Circular __repr__

Decorate __repr__ with @reprlib.recursive_repr() so self-referential objects print ... instead of crashing with RecursionError:

import reprlib

class Node:
    def __init__(self, name: str) -> None:
        self.name = name
        self.children: list[Node] = []

    @reprlib.recursive_repr()
    def __repr__(self) -> str:
        return f"Node({self.name!r}, {self.children!r})"

root = Node("root")
root.children.append(root)
assert repr(root) == "Node('root', [...])"

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes