Search code examples
pythonpretty-print

How to support pretty-printing in custom python 3 classes?


What is the most reliable way for adding pretty-printing support to custom python3 classes?

For interactive data evaluation I found pretty-printing support quite important. However, both iPython's pretty-printer IPython.lib.pretty.pprint and the standard-library pprint.pprint support only builtin structure types by default (lists, tuples, dictionaries), and use the plain repr() for everything else. Notably, this even includes otherwise extremly useful utilities like collections.namedtuple().

As a result, the pretty-printed output is often weirdly formatted.

My current, awkard workaround is to define classes like

class MyPrettyClass(dict):
    def __init__(self, ...):
        self.__dict__ = self
        self._class = self.__class__ # In order to recognize the type.
        ... 
        <A LOT OF FIELDS>
        ...

In a real-world example this resulted in

{'__lp_mockup_xml': <lxml.etree._ElementTree object at 0x0000021C5EB53DC8>,
 '__lp_mockup_xml_file': 'E:\\DataDirectory\\mockup.xml',
 '__lp_realrun_xml_file': 'E:\\DataDirectory\\realrun.xml',
 '_class': <class '__main__.readall'>,
 '_docopy': False,
 'dirname': 'E:\\DataDirectory'}

Is there any better method to get pretty-printing support?

Weakly related: My question Lowlevel introspection in python3? was originally aimed at building my own class-agnostic pretty-printer, but yielded no results.


Solution

  • For ipython, the pretty-printer will look for the _repr_pretty_ method before defaulting to __repr__.

    More details about this function can be find in the ipython doc

    With pprint, the only way I know of is to customize __repr__.