pprint
不寻找任何挂钩.pprint.PrettyPrinter
改用dispatch pattern;类上的一系列方法,这些方法被键入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__
方法的类型!
你也可以直接将函数插入PrettyPrinter._dispatch
字典;self
是显式传入的.对于第三方库来说,这可能是更好的 Select :
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
其他分派方法是如何编写的,请参见pprint
module source code.
和往常一样,像_dispatch
这样的单下划线名称是内部实现细节,可以在future 的版本中更改.然而,这是你在这里的最佳 Select .调度表增加了in Python 3.5个,至少在Python 3.5-3.9 alpha中存在.