IPython ignores __repr__ object when printing it

I wrote a subclass defaultdict, and I gave it my own method __repr__to customize its appearance in an interactive session.

In a regular Python session, this works as expected:

Python 3.5.0 (default, Sep 20 2015, 11:28:25) 
[GCC 5.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> class Foo(defaultdict):
...   def __repr__(self):
...     return 'foo_repr'
... 
>>> foo = Foo()
>>> foo
foo_repr

... but in IPython this is not so:

In [1]: from collections import defaultdict

In [2]: class Foo(defaultdict):
   ...:     def __repr__(self):
   ...:         return 'foo_repr'
   ...:     

In [3]: foo = Foo()

In [4]: foo
Out[4]: defaultdict(None, {})

In [5]: repr(foo), str(foo)
Out[5]: ('foo_repr', 'foo_repr')

What is IPython doing here and how can I stop it?

EDIT: definition _repr_pretty_helps:

In [1]: from collections import defaultdict

In [2]: class Foo(defaultdict):
    def __repr__(self):
        return 'foo_repr'
    def _repr_pretty_(self, p, cycle):
        p.text('repr_foo_pretty')
   ...:         

In [3]: foo = Foo()

In [4]: foo
Out[4]: repr_foo_pretty

But I still do not quite understand what is happening. Obviously, it _repr_prettywas not previously defined on any of the base classes. How does IPython come to be used defaultdict __repr__instead Fooand why does this happen to defaultdictand not many others?

+4
source share

Source: https://habr.com/ru/post/1614721/


All Articles