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

1

7

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.

Gretchen answered 15/3, 2017 at 16:42 Comment(2)
Might be related: #3258572Impede
There's also the way of registering with the formatter python - How can I configure ipython to display integers in hex format? - Stack Overflow but implementing a method inside the class itself is certainly cleaner.Impede
I
3

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__.

Interlock answered 27/11, 2018 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.