By default, when IPython displays an object, it seems to use __repr__
.
__repr__
is supposed to produce a unique string which could be used to reconstruct an object, given the right environment.
This is distinct from __str__
, which supposed to produce human-readable output.
Now suppose we've written a particular class and we'd like IPython to produce human readable output by default (i.e. without explicitly calling print
or __str__
).
We don't want to fudge it by making our class's __repr__
do __str__
's job.
That would be breaking the rules.
Is there a way to tell IPython to invoke __str__
by default for a particular class?
This is certainly possible; you just need implement the instance method
_repr_pretty_(self)
. This is described in the documentation forIPython.lib.pretty
. Its implementation could look something like this:The
p
parameter is an instance ofIPython.lib.pretty.PrettyPrinter
, whose methods you should use to output the text representation of the object you're formatting. Usually you will usep.text(text)
which just adds the giventext
verbatim to the formatted representation, but you can do things like starting and ending groups if your class represents a collection.The
cycle
parameter is a boolean that indicates whether a reference cycle is detected - that is, whether you're trying to format the object twice in the same call stack (which leads to an infinite loop). It may or may not be necessary to consider it depending on what kind of object you're using, but it doesn't hurt.As a bonus, if you want to do this for a class whose code you don't have access to (or, more accurately, don't want to) modify, or if you just want to make a temporary change for testing, you can use the IPython display formatter's
for_type
method, as shown in this example of customizingint
display. In your case, you would usewith
MyObject
of course representing the type you want to customize the printing of. Note that the lambda function carries the same signature as_repr_pretty_
, and works the same way.