How can I make my class pretty printable in Python?

Python has a beautiful printer ( pprint(...)). I would like to make my classes pretty printable. Would printing print my instances better if I provide a specific interface?

The Python documentation in section 8.11 shows different examples, but there is no example on how to make a user-defined class printable. A.

What is the interface for my classes for?
Is there another (possibly better) formatter?


Use Case:

I want to prettyly print the contents of ConfigParser , for which I created an extended version called ExtendenConfigParser . Therefore, I have the opportunity to add additional features or add a suitable print interface. A.

+4
source share
1 answer

pprintnot looking for any hooks. Instead pprint.PrettyPrinter, a send pattern is used; A number of methods in the class that are referenced class.__repr__.

You can subclass pprint.PrettyPrinterto teach it a 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

, YourType . , , __repr__!

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

pprint , .

, , _dispatch, , . , , .

+7

Source: https://habr.com/ru/post/1662060/


All Articles