reprlib.rst 5.07 KB

:mod:`reprlib` --- Alternate :func:`repr` implementation

Source code: :source:`Lib/reprlib.py`


The :mod:`reprlib` module provides a means for producing object representations with limits on the size of the resulting strings. This is used in the Python debugger and may be useful in other contexts as well.

This module provides a class, an instance, and a function:

Class which provides formatting services useful in implementing functions similar to the built-in :func:`repr`; size limits for different object types are added to avoid the generation of representations which are excessively long.

In addition to size-limiting tools, the module also provides a decorator for detecting recursive calls to :meth:`__repr__` and substituting a placeholder string instead.

Repr Objects

:class:`Repr` instances provide several attributes which can be used to provide size limits for the representations of different object types, and methods which format specific object types.

Subclassing Repr Objects

The use of dynamic dispatching by :meth:`Repr.repr1` allows subclasses of :class:`Repr` to add support for additional built-in object types or to modify the handling of types already supported. This example shows how special support for file objects could be added:

import reprlib
import sys

class MyRepr(reprlib.Repr):
    def repr_file(self, obj, level):
        if obj.name in ['<stdin>', '<stdout>', '<stderr>']:
            return obj.name
        else:
            return repr(obj)

aRepr = MyRepr()
print(aRepr.repr(sys.stdin))         # prints '<stdin>'