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.
此模块提供了一个类、一个实例和一个函数:
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'>
在 3.2 版本新加入.
Repr 物件¶
Repr
实例对象包含一些属性可以用于为不同对象类型的表示提供大小限制,还包含一些方法可以格式化特定的对象类型。
- Repr.fillvalue¶
This string is displayed for recursive references. It defaults to
...
.在 3.11 版本新加入.
- Repr.maxlevel¶
创建递归表示形式的深度限制。 默认为
6
。
- Repr.maxdict¶
- Repr.maxlist¶
- Repr.maxtuple¶
- Repr.maxset¶
- Repr.maxfrozenset¶
- Repr.maxdeque¶
- Repr.maxarray¶
表示命名对象类型的条目数量限制。 对于
maxdict
的默认值为4
,对于maxarray
为5
,对于其他则为6
。
- Repr.maxlong¶
表示整数的最大字符数量。 数码会从中间被丢弃。 默认值为
40
。
- Repr.maxstring¶
表示字符串的字符数量限制。 请注意字符源会使用字符串的“正常”表示形式:如果表示中需要用到转义序列,在缩短表示时它们可能会被破坏。 默认值为
30
。
- 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 对象¶
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>