reprlib
— Alternaterepr()
implementation¶
Source code:Lib/reprlib.py
Thereprlib
module provides a means for producing object representationswith limits on the size of the resulting strings. This is used in the Pythondebugger and may be useful in other contexts as well.
This module provides a class, an instance, and a function:
- classreprlib.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)¶
Class which provides formatting services useful in implementing functionssimilar to the built-in
repr()
; size limits for different object typesare added to avoid the generation of representations which are excessively long.The keyword arguments of the constructor can be used as a shortcut to set theattributes of the
Repr
instance. Which means that the followinginitialization:aRepr=reprlib.Repr(maxlevel=3)
Is equivalent to:
aRepr=reprlib.Repr()aRepr.maxlevel=3
See sectionRepr Objects for more information about
Repr
attributes.Changed in version 3.12:Allow attributes to be set via keyword arguments.
- reprlib.aRepr¶
This is an instance of
Repr
which is used to provide therepr()
function described below. Changing the attributes of thisobject will affect the size limits used byrepr()
and the Pythondebugger.
- reprlib.repr(obj)¶
This is the
repr()
method ofaRepr
. It returns a stringsimilar to that returned by the built-in function of the same name, but withlimits on most sizes.
In addition to size-limiting tools, the module also provides a decorator fordetecting recursive calls to__repr__()
and substituting aplaceholder string instead.
- @reprlib.recursive_repr(fillvalue='...')¶
Decorator for
__repr__()
methods to detect recursive calls within thesame thread. If a recursive call is made, thefillvalue is returned,otherwise, the usual__repr__()
call is made. For example:>>>fromreprlibimportrecursive_repr>>>classMyList(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
instances provide several attributes which can be used to providesize limits for the representations of different object types, and methodswhich format specific object types.
- Repr.fillvalue¶
This string is displayed for recursive references. It defaults to
...
.Added in version 3.11.
- Repr.maxlevel¶
Depth limit on the creation of recursive representations. The default is
6
.
- Repr.maxdict¶
- Repr.maxlist¶
- Repr.maxtuple¶
- Repr.maxset¶
- Repr.maxfrozenset¶
- Repr.maxdeque¶
- Repr.maxarray¶
Limits on the number of entries represented for the named object type. Thedefault is
4
formaxdict
,5
formaxarray
, and6
forthe others.
- Repr.maxlong¶
Maximum number of characters in the representation for an integer. Digitsare dropped from the middle. The default is
40
.
- Repr.maxstring¶
Limit on the number of characters in the representation of the string. Notethat the “normal” representation of the string is used as the character source:if escape sequences are needed in the representation, these may be mangled whenthe representation is shortened. The default is
30
.
- Repr.maxother¶
This limit is used to control the size of object types for which no specificformatting method is available on the
Repr
object. It is applied in asimilar manner asmaxstring
. The default is20
.
- Repr.indent¶
If this attribute is set to
None
(the default), the output is formattedwith no line breaks or indentation, like the standardrepr()
.For example:>>>example=[...1,'spam',{'a':2,'b':'spam eggs','c':{3:4.5,6:[]}},'ham']>>>importreprlib>>>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 levelis 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 itwas 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)¶
The equivalent to the built-in
repr()
that uses the formatting imposed bythe instance.
- Repr.repr1(obj,level)¶
Recursive implementation used by
repr()
. This uses the type ofobj todetermine which formatting method to call, passing itobj andlevel. Thetype-specific methods should callrepr1()
to perform recursive formatting,withlevel-1
for the value oflevel in the recursive call.
- Repr.repr_TYPE(obj,level)
Formatting methods for specific types are implemented as methods with a namebased on the type name. In the method name,TYPE is replaced by
'_'.join(type(obj).__name__.split())
. Dispatch to these methods ishandled byrepr1()
. Type-specific methods which need to recursivelyformat a value should callself.repr1(subobj,level-1)
.
Subclassing Repr Objects¶
The use of dynamic dispatching byRepr.repr1()
allows subclasses ofRepr
to add support for additional built-in object types or to modifythe handling of types already supported. This example shows how special supportfor file objects could be added:
importreprlibimportsysclassMyRepr(reprlib.Repr):defrepr_TextIOWrapper(self,obj,level):ifobj.namein{'<stdin>','<stdout>','<stderr>'}:returnobj.namereturnrepr(obj)aRepr=MyRepr()print(aRepr.repr(sys.stdin))# prints '<stdin>'
<stdin>