Search code examples
pythonipython

Making an object's pretty-print representation different if it appears at top-level compared to nested


In IPython, it is possible to make an object have a custom pretty-print representation as explained in How to pretty print object representation in IPython :

class MyObject:
    def _repr_pretty_(self, p, cycle):
        p.text("<MyObject: object content>")

Then in the shell, the pretty-printed output will be:

In [5]: MyObject()
Out[5]: <MyObject: object content>

However, if multiple MyObject() objects appear in a list/dictionary etc., then it may get long.

In [6]: [MyObject(), MyObject()]
Out[6]: [<MyObject: object content>, <MyObject: object content>]

I want to do the following:

  • If MyObject() appears at top level, the long description as above appears.
  • If it appears nested, the representation should be replaced with <MyObject: ...>.

My reasoning: having too much content will clutter the user's view, and if the user wants to see what is the detail inside, they can simply write list[0].

How can I implement that in IPython shell? Or, is there any better approach to this problem?


Solution

  • You can define _ipython_display_().

    class MyObject:
        def _ipython_display_(self):
            print("<MyObject: object content>")
    
        def _repr_pretty_(self, p, cycle):
            p.text("<MyObject: ...>")
    
    In [20]: MyObject()
    Out[20]: <MyObject: object content>
    
    In [21]: [MyObject(), MyObject()]
    Out[21]: [<MyObject: ...>, <MyObject: ...>]