Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pretty print object representation in IPython

Tags:

ipython

IPython outputs list representation in a pretty way by default:

In [1]: test_list
Out[1]: [<object_1>,
         <object_2>,
         <object_3>]

I have object like:

class TestObject(object):
    def __init__(self):
        self._list = [<object_1>, <object_2>, <object_3>]

    def __repr__(self):
        return self._list.__repr__()

test_object = Test()

And IPython representation of this is:

In [2]: test_list
Out[2]: [<object_1>, <object_2>, <object_3>]

Is there a way to get list's way of the representation for my object?

like image 946
Domen Blenkuš Avatar asked Oct 22 '16 14:10

Domen Blenkuš


1 Answers

To get the pretty-printed repr of a list, or any object, call:

from IPython.lib.pretty import pretty
pretty(obj)

If you want your object to have a pretty repr separate from its normal repr (e.g. so it doesn't need IPython to repr() it), you can define a _repr_pretty_(self, cycle=False) method. The cycle parameter will be true if the representation recurses - e.g. if you put a container inside itself.

like image 171
Thomas K Avatar answered Nov 15 '22 02:11

Thomas K