Search code examples
ipythonmixinsrepr

How to implement _repr_pretty in a Python mixin?


Following this discussion, I tried to include _repr_pretty in a mixin.

Without the mixin, it works as expected:

>>> class MyClass():
...     def __repr__(self):
...         return "The Repr."
...     def __str__(self):
...         return "The str."
...     def _repr_pretty_(self, p, cycle):
...         p.text(str(self) if not cycle else '...')
>>> my_object = MyClass()
>>> my_object
The str.

But if I move the _repr_pretty into a mixin, it does not work anymore:

>>> class MyMixin:
...     def _repr_pretty_(self, p, cycle):
...         p.text(str(self) if not cycle else '...')
>>> class MyClass(MyMixin):
...     def __repr__(self):
...         return "The Repr."
...     def __str__(self):
...         return "The str."
>>> my_object = MyClass()
>>> my_object
The Repr.

Any ideas?


Solution

  • In fact it's not a bug, it's a feature... It is explained here:

    In summary, when you write your own __repr__ in a subclass, it takes precedence over a _repr_pretty_ of a parent class. The philosophy behind it is that in that kind of case, you typically want your custom __repr__ method to be used by the IPython pretty printer also.

    Here is a possible workaround:

    >>> class MyMixin:
    >>>     def _my_repr_(self):
    ...         raise NotImplementedError
    >>>     def __repr__(self):
    ...         return self._my_repr_()
    >>>     def _repr_pretty_(self, p, cycle):
    ...         p.text(str(self) if not cycle else '...')
    >>> class MyClass(MyMixin):
    ...     def __init__(self):
    ...         super().__init__()
    ...     def _my_repr_(self):
    ...         return "The Repr."
    ...     def __str__(self):
    ...         return "The str."
    >>> my_object = MyClass()
    >>> my_object
    The str.