Tell IPython to use an object's `__str__` instead of `__repr__` for output

3.5k views Asked by At

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?

1

There are 1 answers

0
David Z On BEST ANSWER

This is certainly possible; you just need implement the instance method _repr_pretty_(self). This is described in the documentation for IPython.lib.pretty. Its implementation could look something like this:

class MyObject:
    def _repr_pretty_(self, p, cycle):
       p.text(str(self) if not cycle else '...')

The p parameter is an instance of IPython.lib.pretty.PrettyPrinter, whose methods you should use to output the text representation of the object you're formatting. Usually you will use p.text(text) which just adds the given text 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 customizing int display. In your case, you would use

get_ipython().display_formatter.formatters['text/plain'].for_type(
    MyObject,
    lambda obj, p, cycle: p.text(str(obj) if not cycle else '...')
)

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