2 min read

Python Reprlib Module

The reprlib module provides a version of repr() that produces abbreviated representations of large or deeply nested containers. It is useful for debugging or logging where you want a concise summary of an object without flooding the output.

Importing the Module

import reprlib

Basic Usage

reprlib.repr()

The reprlib.repr() function works like the built-in repr(), but it limits the size of the resulting string.

import reprlib

long_list = list(range(100))
print(reprlib.repr(long_list))
# Output: [0, 1, 2, 3, 4, 5, ...]

The Repr Class

The reprlib module provides a Repr class which you can use to customize the formatting. It has several attributes that control the limits.

Attributes

  • maxlevel: Depth of recursion (default 6).
  • maxdict: Number of entries for dictionaries (default 4).
  • maxlist: Number of entries for lists (default 6).
  • maxtuple: Number of entries for tuples (default 6).
  • maxset: Number of entries for sets (default 6).
  • maxfrozenset: Number of entries for frozensets (default 6).
  • maxdeque: Number of entries for deques (default 6).
  • maxarray: Number of entries for arrays (default 5).
  • maxlong: Maximum number of characters for long integers (default 40).
  • maxstring: Maximum number of characters for strings (default 30).
  • maxother: Maximum number of characters for other types (default 20).

Customizing Limits

import reprlib

a_repr = reprlib.Repr()
a_repr.maxlist = 4
a_repr.maxstring = 10

print(a_repr.repr(list(range(100))))
# Output: [0, 1, 2, 3, ...]

print(a_repr.repr("This is a very long string"))
# Output: 'This is a ...'

Customizing Representation

You can subclass Repr to add support for your own types or modify existing behavior. You define methods named repr_TypeName.

import reprlib

class MyRepr(reprlib.Repr):
    def repr_MyClass(self, obj):
        return f'<MyClass with {len(obj.data)} items>'

class MyClass:
    def __init__(self):
        self.data = list(range(100))

obj = MyClass()
my_repr = MyRepr()
print(my_repr.repr(obj))
# Output: <MyClass with 100 items>

Recursive Representation

The @reprlib.recursive_repr() decorator can be used on __repr__ methods to detect recursive calls.

import reprlib

class MyList(list):
    @reprlib.recursive_repr()
    def __repr__(self):
        return '<' + '|'.join(map(repr, self)) + '>'

m = MyList('abc')
m.append(m)
m.append('x')
print(m)
# Output: <'a'|'b'|'c'|...|'x'>

programming/python/python