reprlib — Альтернативна реалізація repr()

Вихідний код: Lib/reprlib.py


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

Цей модуль надає клас, екземпляр і функцію:

class reprlib.Repr(*, maxlevel=6, maxtuple=6, maxlist=6, maxarray=5, maxdict=4, maxset=6, maxfrozenset=6, maxdeque=6, maxstring=30, maxlong=40, maxother=30, fillvalue='...', indent=None)

Клас, який надає служби форматування, корисні для реалізації функцій, подібних до вбудованих repr(); обмеження розміру для різних типів об’єктів додано, щоб уникнути генерації представлень, які є надмірно довгими.

The keyword arguments of the constructor can be used as a shortcut to set the attributes of the Repr instance. Which means that the following initialization:

aRepr = reprlib.Repr(maxlevel=3)

Еквівалентно:

aRepr = reprlib.Repr()
aRepr.maxlevel = 3

See section Repr Objects for more information about Repr attributes.

Змінено в версії 3.12: Allow attributes to be set via keyword arguments.

reprlib.aRepr

Це екземпляр Repr, який використовується для надання функції repr(), описаної нижче. Зміна атрибутів цього об’єкта вплине на обмеження розміру, які використовуються repr() і налагоджувачем Python.

reprlib.repr(obj)

Це метод repr() для aRepr. Він повертає рядок, подібний до того, який повертає однойменна вбудована функція, але з обмеженнями на більшість розмірів.

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

@reprlib.recursive_repr(fillvalue='...')

Decorator for __repr__() methods to detect recursive calls within the same thread. If a recursive call is made, the fillvalue is returned, otherwise, the usual __repr__() call is made. For example:

>>> from reprlib import recursive_repr
>>> class MyList(list):
...     @recursive_repr()
...     def __repr__(self):
...         return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>

Added in version 3.2.

Repr Objects

Екземпляри Repr надають кілька атрибутів, які можна використовувати для встановлення обмежень розміру для представлень різних типів об’єктів, і методів, які форматують певні типи об’єктів.

Repr.fillvalue

This string is displayed for recursive references. It defaults to ....

Added in version 3.11.

Repr.maxlevel

Обмеження глибини створення рекурсивних представлень. Типовим є 6.

Repr.maxdict
Repr.maxlist
Repr.maxtuple
Repr.maxset
Repr.maxfrozenset
Repr.maxdeque
Repr.maxarray

Обмеження на кількість записів, представлених для названого типу об’єкта. Типовим значенням є 4 для maxdict, 5 для maxarray та 6 для інших.

Repr.maxlong

Максимальна кількість символів у представленні цілого числа. Цифри випадають із середини. Типовим є 40.

Repr.maxstring

Обмеження на кількість символів у представленні рядка. Зауважте, що «звичайне» представлення рядка використовується як джерело символів: якщо в представленні потрібні керуючі послідовності, вони можуть бути спотворені, коли представлення скорочено. Типовим значенням є 30.

Repr.maxother

Це обмеження використовується для керування розміром типів об’єктів, для яких немає спеціального методу форматування для об’єкта Repr. Його застосовують подібним чином до maxstring. Типовим значенням є 20.

Repr.indent

If this attribute is set to None (the default), the output is formatted with no line breaks or indentation, like the standard repr(). For example:

>>> example = [
...     1, 'spam', {'a': 2, 'b': 'spam eggs', 'c': {3: 4.5, 6: []}}, 'ham']
>>> import reprlib
>>> aRepr = reprlib.Repr()
>>> print(aRepr.repr(example))
[1, 'spam', {'a': 2, 'b': 'spam eggs', 'c': {3: 4.5, 6: []}}, 'ham']

If indent is set to a string, each recursion level is placed on its own line, indented by that string:

>>> aRepr.indent = '-->'
>>> print(aRepr.repr(example))
[
-->1,
-->'spam',
-->{
-->-->'a': 2,
-->-->'b': 'spam eggs',
-->-->'c': {
-->-->-->3: 4.5,
-->-->-->6: [],
-->-->},
-->},
-->'ham',
]

Setting indent to a positive integer value behaves as if it was set to a string with that number of spaces:

>>> aRepr.indent = 4
>>> print(aRepr.repr(example))
[
    1,
    'spam',
    {
        'a': 2,
        'b': 'spam eggs',
        'c': {
            3: 4.5,
            6: [],
        },
    },
    'ham',
]

Added in version 3.12.

Repr.repr(obj)

Еквівалент вбудованого repr(), який використовує форматування, накладене екземпляром.

Repr.repr1(obj, level)

Рекурсивна реалізація, яку використовує repr(). Тут використовується тип obj, щоб визначити, який метод форматування викликати, передаючи йому obj і level. Специфічні для типу методи повинні викликати repr1() для виконання рекурсивного форматування з level - 1 для значення level у рекурсивному виклику.

Repr.repr_TYPE(obj, level)

Методи форматування для конкретних типів реалізуються як методи з іменем на основі імені типу. У назві методу TYPE замінюється на '_'.join(type(obj).__name__.split()). Надсилання до цих методів обробляється repr1(). Специфічні для типу методи, які потребують рекурсивного форматування значення, мають викликати self.repr1(subobj, level - 1).

Підкласифікація Repr Objects

The use of dynamic dispatching by Repr.repr1() allows subclasses of 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_TextIOWrapper(self, obj, level):
        if obj.name in {'<stdin>', '<stdout>', '<stderr>'}:
            return obj.name
        return repr(obj)

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