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

你说的曾经没有我的故事 提交于 2019-12-19 17:32:13

问题


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:


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.



来源:https://stackoverflow.com/questions/41453624/tell-ipython-to-use-an-objects-str-instead-of-repr-for-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!