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

43 Views Asked by At

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?

2

There are 2 best solutions below

0
wjandrea On BEST ANSWER

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: ...>]
0
user202729 On

Another way I can find is to access p.group_stack. Unfortunately, group_stack is completely undocumented as far as I can tell, so use it at your own risk.

class MyObject:
    def _repr_pretty_(self, p, cycle):
        if len(p.group_stack)>2:
            p.text("<MyObject: ...>")
        else:
            p.text("<MyObject: object content>")

The output is as expected.

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

In [3]: [MyObject(), MyObject()]
Out[3]: [<MyObject: ...>, <MyObject: ...>]