pprint
不寻找任何钩子。这pprint.PrettyPrinter
uses a 调度模式反而;类上的一系列关键方法class.__repr__
参考。
你可以子类化pprint.PrettyPrinter
教授你的班级:
class YourPrettyPrinter(pprint.PrettyPrinter):
_dispatch = pprint.PrettyPrinter._dispatch.copy()
def _pprint_yourtype(self, object, stream, indent, allowance, context, level):
stream.write('YourType(')
self._format(object.foo, stream, indent, allowance + 1,
context, level)
self._format(object.bar, stream, indent, allowance + 1,
context, level)
stream.write(')')
_dispatch[YourType.__repr__] = _pprint_yourtype
然后直接使用该类来漂亮地打印包含的数据YourType
实例。请注意,这取决于具有自己定制的类型__repr__
method!
您还可以将功能直接插入PrettyPrinter._dispatch
字典;self
是显式传入的。对于第三方库来说,这可能是更好的选择:
from pprint import PrettyPrinter
if isinstance(getattr(PrettyPrinter, '_dispatch'), dict):
# assume the dispatch table method still works
def pprint_ExtendedConfigParser(printer, object, stream, indent, allowance, context, level):
# pretty print it!
PrettyPrinter._dispactch[ExtendedConfigParser.__repr__] = pprint_ExtendedConfigParser
See the pprint模块源代码 https://github.com/python/cpython/blob/3.8/Lib/pprint.py了解如何编写其他调度方法。
与往常一样,单下划线名称如_dispatch
是可以在未来版本中更改的内部实现细节。然而,这是您在这里的最佳选择。添加了调度表在Python 3.5中 https://github.com/python/cpython/commit/8e2aa88a40c0c7611a04696d1789da159e40d7f7并且至少存在于 Python 3.5 - 3.9 alpha 中。
您可能想看看rich https://rich.readthedocs.io/en/stable/introduction.html,一个第三方库,具有一些很棒的漂亮打印功能,并支持钩子(__rich_repr__
);看到有关自定义漂亮打印的文档 https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol.