Python has a pretty printer (
pprint does not look for any hooks. The
pprint.PrettyPrinter uses a dispatch pattern instead; a series of methods on the class that are keyed on
You can subclass
pprint.PrettyPrinter to teach it about your class:
class YourPrettyPrinter(pprint.PrettyPrinter): _dispatch = pprint.PrettyPrinter.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
then use the class directly to pretty print data containing
YourType instances. Note that this is contingent on the type having their own custom
You can also plug functions directly into the
self is passed in explicitly. This is probably the better option for a 3rd-party library:
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 for how the other dispatch methods are written.
As always, single-underscore names like
_dispatch are internal implementation details that can be altered in a future version. However, it is the best option you have here.